简体   繁体   中英

Displaying has_many through association as column in Active Admin index

How do I display a list of has_many_through associations with the association as the column headings and the through: value as an entry in the table row?

I have 3 models:

class Jobs 
  attr_accesor :title 

  has_many :scores 
  has_many :factors, through: :scores 
end 

class Scores 
  attr_accesor :score 

  belongs_to :job 
  belongs_to :factor 
end 

class Factor 
  attr_accesor :name 
  has_many :scores 
  has_many :jobs, through: :scores 
end 

I want to be able to show, in the Jobs index, a row for each Job, the title of each Factor as a column heading, and the scores of each Job as the value in the cell.

I would expect to have to do something like this in the app/admin/jobs.rb file:

index do |jobs|
  column :title
  jobs.scores.each do |score|
    column(score.factor.name) { |score| score.score }
  end
end

And get output like this:

Job              |  Education  |  Experience  |  Leadership  |  ...  |
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CEO              |     600     |     720      |     580      |  ...  |
Admin Assistant  |     210     |     200      |     150      |  ...  |

But activeadmin doesn't seem to like the jobs.scores.each line, giving me the following error:

undefined method `scores' for 
#<ActiveAdmin::Views::IndexAsTable::IndexTableFor:0x00000104d1dad0>

If I understand your data correctly I think this will work. You can do each all on one line, also if that doesn't work look into map or collect. You can also chain each and map. Ensure you're using compact so you don't hit nils. Below I'm assuming the score.factor.name is equal to what each column should be named and what data is filled in.

index do |jobs|
  column :title
  column "Education" do |job|
   job.scores.map { |score| score if score.factor.name == "Education"  }.compact
  end
  column "Experience" do |job|
   job.scores.map { |score| score if score.factor.name == "Experience"  }.compact
  end
end

see this example for Jobs has_many Scores

ActiveAdmin.register Jobs do 
 index do
 :scores do |i|
   table_for i.scores do
     column do |user|
       user.scores
     end
   end
 end
 end
end

this is not the exact solution of your problem but it is an overview that how you can do that..!

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