Rails ActiveAdmin:在同一视图中显示相关资源的表 [英] Rails ActiveAdmin: showing table of a related resource in the same view

查看:44
本文介绍了Rails ActiveAdmin:在同一视图中显示相关资源的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 Rails ActiveAdmin gem 显示资源时,我想显示另一个关联模型的表.

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

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

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.

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

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

推荐答案

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

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

这篇关于Rails ActiveAdmin:在同一视图中显示相关资源的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆