【问题标题】:ActiveAdmin display nested attributes on index pageActiveAdmin 在索引页面上显示嵌套属性
【发布时间】:2017-08-23 00:38:54
【问题描述】:

如何在索引页上以逗号分隔的列显示嵌套资源?

我有 3 个模型

models/job.rb

class Job < ActiveRecord::Base
  validates :title, presence: true
  validates :company, presence: true
  validates :url, presence: true

  has_many :position_type_joins
  has_many :position_types, through: :position_type_joins

  accepts_nested_attributes_for :position_types, :allow_destroy => true    

end

models/position_type.rb

class PositionType < ApplicationRecord

  has_many :position_type_joins
  has_many :jobs, through: :position_type_joins

end

models/position_type_join.rb

class PositionTypeJoin < ApplicationRecord
  belongs_to :job
  belongs_to :position_type
end

我已成功自定义表单页面,因此它现在将职位类型列为复选框,我设置的当前值为“永久、全职、兼职、合同、实习、志愿者”。

我正在努力解决的问题是如何自定义 ActiveAdmin 索引页面,以便出现一个标题为“职位类型”的列,然后每个职位都列出了已分配的职位类型值。例如:

+-------------------+----------------------+
|     Job title     |    Position Type     |
+-------------------+----------------------+
| Painter           | Contract, Part time  |
| Library Assistant | Part time, Volunteer |
+-------------------+----------------------+

我确实在类似的问题中看到了这种语法,但无法让它为我工作。

Show child/nested attributes in ActiveAdmin index view column

index do
  column :code
  column 'Sales Agent' do |client|
    client.sales_agent.agent_name if !client.sales_agent.nil?
  end
end

我尝试根据需要对其进行编辑

index do
    column 'Position type' do |job|
    job.position_type.name if !job.position_type.name?
  end
end

我得到的错误是

undefined method `position_type'

我对 ruby​​ on rails 完全陌生,如果我遗漏了一些明显的东西,非常抱歉。非常感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails activeadmin


    【解决方案1】:

    尝试类似:

    index do
      column 'Position type' do |job|
        job.position_types.map(&:name).join(',')
      end
    end
    

    提高SQL的效率试试:

    controller do
      def scoped_collection
        super.includes(:jobs)
      end
    end
    

    【讨论】:

    • 由于 OP 正在迭代 job.position_types,因此 scoped_collection 应如下所示:super.includes(:position_types)
    【解决方案2】:

    问题是您在job 中调用position_type,但它有很多position_types。所以正确的调用应该是job.position_types,如果有很多,或者如果你只想要第一个job.position_types.first,则遍历它们。

    注意:请记住,这将生成 N+1 个查询,应通过预先加载 scoped_collection 中的关联来解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      相关资源
      最近更新 更多