简体   繁体   中英

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

I got this error

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

I need to display product name

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

here is my codes

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 is array of product ids.

.find will returns an array for objects if you pass multiple ids or array of ids, so .name will not directly work on result as it array .

you can use either of following options

  • Using find & map
    column "product" do |m|
      Product.find(m.product_ids).map(&:name).join(', ')
    end
  • Using where & map
    column "product" do |m|
      Product.where(id: m.product_ids).map(&:name).join(', ')
    end
  • Using 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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM