activeadmin如何显示集合的名称select而不是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
u=Product.find(m.product_ids).name

product_ids是产品ID的数组。

若传递多个id或id的数组,.find将返回对象的数组,所以.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

在MRI 2.6.3上使用Rails 6.0.0,这对我来说很有效:

f.select :product_ids, Product.all.collect { |prod| [prod.name, prod.id] }, {}, { multiple: true }

最新更新