Jhonnatas Alencar
Jhonnatas Alencar

Reputation: 113

Retrieve information from associated model

I have 3 models:

class Brand 
  attr_accessible :obs, :site, :title
  has_many :equipments
end

class Equipment 
  attr_accessible :brand_id, :category_id, :lending_id 
  belongs_to :brand
  has_many :lendings  
end

class Lending  
 attr_accessible :equipment_id 

 belongs_to :equipment
end

I'm trying to show the brand of an associated equipament: Brand: <%= @lending.equipment.brand %> that command show this: Brand:0xab7f2c8

As you can see, there's no association between brand and lending models and for me its strange if i do that. I want to use the equipment/brand association to retrieve the :title information and show it on my lending view.

Can anyone help me?

Upvotes: 0

Views: 34

Answers (2)

PinnyM
PinnyM

Reputation: 35541

You can either use a delegate in Lending:

delegate :brand, :to => :equipment, allow_nil: true

Or you can setup a has-one-through association in Lending:

has_one :branch, :through => :equipment

Either way, you can now call branch directly from a Lending instance, and work on it (almost) as if it were a regular association.

Upvotes: 2

usha
usha

Reputation: 29369

Use delegate

   class Lending  
     attr_accessible :equipment_id 

     belongs_to :equipment
     delegate :brand, :to => :equipment, :allow_nil => true
    end

now you can use

<%= @lending.brand.title%>

Upvotes: 1

Related Questions