~/journal/2024/11/using-hotwire-combobox-with-prefixed-id

在 hotwire-combobox 中使用 prefixed_ids

如何在 Rails 中配置 hotwire-combobox,通过 async_combobox_options 的 `value` 选项返回自定义前缀 ID(如 acct_xxx)。

发布
阅读时间
1 分钟
标签
RailsTips

本页由 AI 从原文翻译。

安装部分我就不说了,直接进入解决方案。

前言

我有一个 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。但有一个问题:返回的值是实际的 database id,而我们想要返回像 acct_xxxxx 这样的值。

答案

原来在 hotwire combobox 中,我们可以把 value 传给 async_combobox_options。现在,我们来操作一下。

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

就这一个简单的改动,现在我们就向前端返回带前缀的值了!

Epona
作者Epona

There's nothing wrong with having a little fun

x.com/simura_epona

相关文章

正在加载评论…