Ton*_*nys 1 ruby ruby-on-rails has-many-through ruby-on-rails-3 activeadmin
如何显示 has_many_through 关联列表,其中关联作为列标题,而 through: 值作为表行中的条目?
我有 3 个模型:
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
Run Code Online (Sandbox Code Playgroud)
我希望能够在 Jobs 索引中显示每个 Job 的一行,每个 Factor 的标题作为列标题,以及每个 Job 的分数作为单元格中的值。
我希望必须在app/admin/jobs.rb文件中做这样的事情:
index do |jobs|
column :title
jobs.scores.each do |score|
column(score.factor.name) { |score| score.score }
end
end
Run Code Online (Sandbox Code Playgroud)
并得到这样的输出:
Job | Education | Experience | Leadership | ... |
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CEO | 600 | 720 | 580 | ... |
Admin Assistant | 210 | 200 | 150 | ... |
Run Code Online (Sandbox Code Playgroud)
但是 activeadmin 似乎不喜欢这jobs.scores.each条线,给我以下错误:
undefined method `scores' for
#<ActiveAdmin::Views::IndexAsTable::IndexTableFor:0x00000104d1dad0>
Run Code Online (Sandbox Code Playgroud)
小智 5
如果我正确理解您的数据,我认为这会起作用。您可以在一行上完成所有操作,如果这不起作用,请查看地图或收集。您还可以链接每个和映射。确保您使用的是 compact,这样您就不会遇到 nils。下面我假设 score.factor.name 等于每列应该命名的内容以及填充的数据。
索引做|工作|
列:标题
栏目“教育”做|工作|
job.scores.map { |分数| 分数 if score.factor.name == "Education" }.compact
结尾
栏目“经验”做|工作|
job.scores.map { |分数| 分数 if score.factor.name == "Experience" }.compact
结尾
结尾