Reputation: 3399
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>
Upvotes: 1
Views: 6996
Reputation: 2932
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..!
Upvotes: -1
Reputation: 183
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
Upvotes: 5