2012-11-16 44 views
10

當使用Rails ActiveAdmin gem編寫資源時,我想顯示另一個關聯模型的表。Rails ActiveAdmin:在同一視圖中顯示相關資源的表格

所以我們假設一個Wineryhas_many:products。現在我想要顯示Winery管理資源的show頁面上的相關產品。我希望這是一張類似於Products資源的index的表格。

我得到它的工作,但只有通過手動重新創建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 

回答

15

爲了解決這個問題,我們使用了諧音:

/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 
+3

謝謝,我想'table_for(集合)'是缺少邏輯片。 –

+0

這幫助我回答[this](http://stackoverflow.com/questions/35236752/how-do-you-add-a-second-column-of-children-without-duplicating-the-parent-co/35256690 #35256690)這個問題。謝謝:) – MilesStanfield

+0

真棒感謝一個奇妙的職位。 –

相關問題