活动管理员如何显示集合名称 select 而不是 id

active admin how to display name of collection select insted of id

我遇到了这个错误

undefined method `name' for #<Array:0x00007fb013333018>

我需要显示产品名称

f.input :product_ids , :as => :select, :collection => Product.all.collect {|product| [product.name, product.id] }

这是我的代码

ActiveAdmin.register Case do
permit_params  :user_id, :product_ids ,:step_ids , :pt_first_name,:pt_last_name, :date_received, :due_date, :shade, 
              :mould, :upper_lower

  index do
    column do |user|
  link_to :id, doctor_path(user.id)
end
    column :pt_first_name
    column :pt_last_name
    column "product" do |m|
      u=Product.find(m.product_ids).name
    end
    column :user
    column :product
    column :sign_in_count
    column :created_at
    actions
  end
  
form do |f|
        f.inputs do
        f.input :user
        f.input :pt_first_name
        f.input :pt_last_name
        f.input :date_received
        f.input :due_date
        f.input :shade
        f.input :mould
        f.input :upper_lower
        f.input :product_ids , :as => :select, :collection => Product.all.collect {|product| [product.name, product.id] }
        f.input :step_ids , :as => :select, :collection => Step.all.collect {|step| [step.name, step.id] }
        end
        actions 
      end


end

在 MRI 2.6.3 上使用 Rails 6.0.0,这对我有用:

f.select :product_ids, Product.all.collect { |prod| [prod.name, prod.id] }, {}, { multiple: true }
u=Product.find(m.product_ids).name

product_ids 是产品 ID 数组。

如果您传递多个 ID 或 ID 数组,

.find 将 returns 对象数组,因此 .name 不会像 array 那样直接作用于结果。

您可以使用以下任一选项

  • 使用 find & map
    column "product" do |m|
      Product.find(m.product_ids).map(&:name).join(', ')
    end
  • 使用 where & map
    column "product" do |m|
      Product.where(id: m.product_ids).map(&:name).join(', ')
    end
  • 使用 where & pluck
    column "product" do |m|
      Product.where(id: m.product_ids).pluck(:name).join(', ')
    end