Rails ActiveAdmin: showing table of a related resource in the same view

我们两清 提交于 2021-02-05 20:30:31

问题


When showing a resource using the Rails ActiveAdmin gem, I want to show a table of another associated model.

So let's say a Winery has_many :products. Now I want to show the products associated on the show page of the Winery admin resource. And I want that to be a table similar to what I would get on the index of the Products resource.

I got it to work, but only by recreating the HTML structure manually, which kind of sucks. Is there a cleaner way to create an index table style view for a specific subset of an associated resource?

What I have, which kinda sucks:

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

回答1:


To solve this problem, we used partials:

/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


来源:https://stackoverflow.com/questions/13422751/rails-activeadmin-showing-table-of-a-related-resource-in-the-same-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!