10

show使用 Rails ActiveAdmin gem 获取资源时,我想显示另一个关联模型的表格。

所以让我们说一个Winery has_many :products. 现在我想在管理资源的show页面上显示关联的产品。Winery我希望它是一个类似于我indexProducts资源中获得的表格。

我让它工作,但只能通过手动重新创建 HTML 结构,这很糟糕。是否有一种更简洁的方法index可以为关联资源的特定子集创建表格样式视图?

我有什么,有点糟糕:

show title: :name do |winery|
  attributes_table do
    row :name
    row(:region) { |o| o.region.name }
    rows :primary_contact, :description
  end

  # This is the part that sucks.
  div class: 'panel' do
    h3 'Products'
    div class: 'attributes_table' do
      table do
        tr do
          th 'Name'
          th 'Vintage'
          th 'Varietal'
        end
        winery.products.each do |product|
          tr do
            td link_to product.name, admin_product_path(product)
            td product.vintage
            td product.varietal.name
          end
        end
      end
    end
  end
end
4

1 回答 1

18

为了解决这个问题,我们使用了部分:

/app/admin/wineries.rb

ActiveAdmin.register Winery do
  show title: :name do
    render "show", context: self
  end
end

app/admin/products.rb

ActiveAdmin.register Product do
  belongs_to :winery
  index do
    render "index", context: self
  end
end

/app/views/admin/wineries/_show.builder

context.instance_eval  do
  attributes_table do
    row :name
    row :region
    row :primary_contact
  end
  render "admin/products/index", products: winery.products, context: self
  active_admin_comments
end

/app/views/admin/products/_index.builder

context.instance_eval  do
  table_for(invoices, :sortable => true, :class => 'index_table') do
    column :name
    column :vintage
    column :varietal
    default_actions rescue nil # test for responds_to? does not work.
  end
end
于 2012-11-17T09:10:13.753 回答