Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display associated model's attribute in Active Admin index with belongs_to/has_many relationship (Rails 3.2/Active Admin)

I'm building a daily deal Rails app to learn RoR.

I am facing a problem for the past few hours : i can't get a model's attribute of an other associated model on active admin. Let me show you exactly the problem :

I have two models: Brand (i.e the brand of the deal) and Deal. A deal belongs to a Brand but a Brand can have many Deals.

models/deal.rb is like this:

class Deal < ActiveRecord::Base
  belongs_to :brand

and we have models/brand.rb:

class Brand < ActiveRecord::Base    
  has_many :deals

  attr_accessible :name

And i did the t.belongs_to in my migrations so this is ok.

In Active Admin's Deals' create form , i type, as admin, which brand the deal is associated with:

admin/game.rb

ActiveAdmin.register Deal do
# -- Form -----------------------------------------------------------
  form do |f|
    f.inputs "Brand (i.e. client)" do
      f.input :brand_id, :label => "Select a brand:", :as => :select, :collection => Brand.all
    end

it works great, and i can create Deals with a certain brand. but I CAN'T manage to display the NAME of the Brand in my list of Deals:

ActiveAdmin.register Deal do
index do   
selectable_column   
# id_column 
column :title
column :deal_amount
column :brand do |deal|
  link_to deal.brand.name
end

...doesn't work.

How can I do that ?

I tried everything but i basically don't know how to fetch the name of a Brand given it matches the brand_id in the Deal's table.

Any help appreciated.

like image 920
Mathieu Avatar asked Feb 16 '23 00:02

Mathieu


1 Answers

show do |f|
  panel "Subject" do
    attributes_table_for f, :name, :description, :is_visible
  end

  panel "Pages in List View" do
    table_for(f.pages) do |page|
      column :name
      column :permalink
      column :is_visible
    end
  end

  panel "Pages in View " do
    div_for(f.pages) do |page|
      panel page.name do
        attributes_table_for page, :name, :description, :is_visible
      end
    end
  end

end

end

You can do nested relations in same style as parent model

like image 63
Ali Abbas Avatar answered Apr 27 '23 12:04

Ali Abbas