安装部分我就不说了,直接进入解决方案。
前言
我有一个 Account 模型,想和 hotwire combobox 一起用,并且通过 [prefixedids](https://github.com/excid3/prefixed_ids) 设置了带前缀的 ID。代码如下。
class Account < ApplicationRecord
has_prefix_id :acct
# Later to be used in async search options
scope :search, ->(q) { q.blank? ? all : where("name like ?", "%#{q}%") }
# we need to define this function, so that hotwire combobox can render.
def to_combobox_display
name
end
end配置 hotwire combobox
首先,把它加到表单里。
<%= f.combobox :account_id, accounts_path %>然后,在我们的控制器里设置查询。
class AccountsController < ApplicationController
def index
@accounts = Account.search(params[:q])
end
end在 erb 文件(hint: we are using turbo_stream.erb, not the regular html.erb)中。
<%# app/views/accounts/index.turbo_stream.erb %>
<%= async_combobox_options @accounts,
render_in: { partial: "accounts/account", next_page: nil } %><%# app/views/accounts/_account.turbo_stream.erb %>
<div>
<%= account.name %>
</div>现在,我们有了一个能用的 hotwire combobox。但有一个问题:返回的值是实际的 database id,而我们想要返回像 acct_xxxxx 这样的值。
答案
原来在 hotwire combobox 中,我们可以把 value 传给 async_combobox_options。现在,我们来操作一下。
<%= async_combobox_options @accounts,
render_in: { partial: "accounts/account", next_page: nil, },
value: :to_param
%>就这一个简单的改动,现在我们就向前端返回带前缀的值了!

正在加载评论…