【问题标题】:Displaying has_many through association as column in Active Admin index通过关联显示 has_many 作为 Active Admin 索引中的列
【发布时间】:2013-03-18 11:15:19
【问题描述】:

如何显示 has_many_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 

我希望能够在 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

得到这样的输出:

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

但 activeadmin 似乎不喜欢 jobs.scores.each 行,给我以下错误:

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

【问题讨论】:

  • 我认为 Muhamamd Awais 是对的,我认为你需要改变你的方法。首先确保您遍历作业,因此您有 job.scores 因为它现在不知道要找到分数,除非您遍历每个单独的对象。其次,将其视为 erb 文件。 AA 中的所有内容都已打印 - 因此,当您说 job.scores.each 时,它实际上会像 而不是 。让我知道这是否有意义
  • 谢谢Eileen,第二点是新的,我没有这么想。第一个是有道理的,但我无法弄清楚如何在 index 块的上下文中循环作业以到达 job.scores。在这方面的任何帮助都会很棒。

标签: ruby-on-rails ruby ruby-on-rails-3 activeadmin has-many-through


【解决方案1】:

如果我正确理解您的数据,我认为这会起作用。您可以在一条线上完成所有操作,如果这不起作用,请查看地图或收集。您还可以链接每个和映射。确保 你正在使用紧凑型,所以你不会打零。下面我假设 score.factor.name 等于每列应该命名的内容和填写的数据。

索引做|工作| 列:标题 “教育”栏目 |job| job.scores.map { |分数|如果 score.factor.name == "教育" }.compact 则得分 结尾 “经验”栏目做|工作| job.scores.map { |分数| score if score.factor.name == "经验" }.compact 结尾 结尾

【讨论】:

  • 再次感谢艾琳,这看起来可能会起作用,除了因素名称(EducationExperience)是我试图找出循环的内容。本质上,我需要提取相关的名称 - 他们不会事先知道。
【解决方案2】:

请参阅此示例以了解 Jobs has_many 分数

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

这不是您问题的确切解决方案,但它是您如何做到这一点的概述......!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多