Mathieu
Mathieu

Reputation: 4787

Can't display in Active Admin index attribute of associated model (belongs_to/has_many) - Rails 3.2

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/deal.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 iun Active Admin'x index :

ActiveAdmin.register Deal do
index do   
  selectable_column   
  # id_column 
  column :title
  column :deal_amount
  column :brand do |deal|
    link_to deal.brand.name, admin_brand_path(deal.brand)
  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.

UPDATE the error i'm getting is it doesn't understand function .name: unknown method 'name'

Upvotes: 2

Views: 2628

Answers (2)

Josh Kovach
Josh Kovach

Reputation: 7749

You need to handle the case of deal.brand being nil.

ActiveAdmin.register Deal do
  index do   
    selectable_column   
    # id_column 
    column :title
    column :deal_amount
    column :brand do |deal|
      if deal.brand.present?
        link_to deal.brand.name, admin_brand_path(deal.brand)
      else
        status_tag('Empty')
      end
    end
  end
end

Upvotes: 4

Jeremy Green
Jeremy Green

Reputation: 8574

Your :brand column looks correct to me. If you find a deal in the console what do you get if do deal.brand and deal.brand.name?

Upvotes: 0

Related Questions