このページは原文を AI が翻訳したものです。
インストール部分は省略して、直接解決策に進みます。
前置き
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
endhotwire combobox のセットアップ
まず、フォームに追加します。
<%= f.combobox :account_id, accounts_path %>次に、コントローラーでクエリを設定します。
class AccountsController < ApplicationController
def index
@accounts = Account.search(params[:q])
end
enderb ファイル(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 ができました。ただし、1つ問題があります。返ってくる値が実際の database id なのですが、acct_xxxxx のような値を返してほしいのです。
答え
hotwire combobox では、async_combobox_options に value を渡せるということがわかりました。では、やってみましょう。
<%= async_combobox_options @accounts,
render_in: { partial: "accounts/account", next_page: nil, },
value: :to_param
%>この1つの簡単な変更で、プレフィックス付きの値をフロントエンドに返せるようになりました!


コメントを読み込み中…