~/adventure-log/2024/11/using-hotwire-combobox-with-prefixed-id
テックこのページは原文を AI が翻訳したものです。

hotwire-combobox を prefixed_ids と一緒に使う

Rails で hotwire-combobox を設定し、`value` オプションを async_combobox_options に渡して、カスタムのプレフィックス付き ID(acct_xxx など)を返す方法。

公開
読了時間
1 分
タグ
RailsTips

インストール部分は省略して、直接解決策に進みます。

前置き

Account モデルを hotwire combobox で使いたいと思っていて、[prefixedids](https://github.com/excid3/prefixed_ids) を使ってプレフィックス付きのIDを設定しました。コードはこちらです。

ruby
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 のセットアップ

まず、フォームに追加します。

erb
<%= f.combobox :account_id, accounts_path %>

次に、コントローラーでクエリを設定します。

ruby
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)内で。

erb
<%# app/views/accounts/index.turbo_stream.erb %>
<%= async_combobox_options @accounts, 
    render_in: { partial: "accounts/account", next_page: nil } %>
erb
<%# app/views/accounts/_account.turbo_stream.erb %>
<div>
  <%= account.name %>
</div>

これで、動作する hotwire combobox ができました。ただし、1つ問題があります。返ってくる値が実際の database id なのですが、acct_xxxxx のような値を返してほしいのです。

答え

hotwire combobox では、async_combobox_options に value を渡せるということがわかりました。では、やってみましょう。

erb
<%= async_combobox_options @accounts,
    render_in: { partial: "accounts/account", next_page: nil, },
    value: :to_param
%>

この1つの簡単な変更で、プレフィックス付きの値をフロントエンドに返せるようになりました!

収集品を手に入れた· Item get

No.004

古代の軸芯

ノーマル

地方
古代技術の高地
生息地
Rails · Tips
発見日
冒険時間
1 分

この冒険を読み終えて手に入れた。読む人が増えるほど、レア度が上がる。

Epona
執筆Epona

There's nothing wrong with having a little fun

x.com/simura_epona

関連記事Nearby quests

コメントを読み込み中…