Bastien
Bastien

Reputation: 606

Rails retrieving associated information

I fail to find the correct syntax to retrieve associated information. I have a model 'companyaccount' that belongs to a model 'company'.

class Company < ActiveRecord::base
  has_many :companyaccounts
end

class Companyaccount < ActiveRecord::base
  belongs_to :company
end

In the View, I can easily retrieve both the 'Companyaccount' 'number' and the 'id' of the associated company through the 'company_id' field of the 'companyaccount' table.

<%= @companyaccount.each do |companyaccount| %>
 <%= companyaccount.company_id %>
 <%= companyaccount.number %>
<% end %>

The View is called from this basic Controller

def index
  @companyaccount = Companyaccount.all
end

Now, I do not want to have the company_id but the actual name of the company (housed in the 'company' table). I manage to do it for one specific company using a controller like this

def index
  @companyaccount = Companyaccount.all
  @company = Company.first
end

and then in the view change

<%= companyaccount.company_id %>

by

<%= company.name %>

but of course, this will retrieve, for each companyaccount, the same first company and not each of the company associated with the companyaccount. Could anyone provide me with the appropriate syntax to retrieve the associated company's name for each companyaccount in the "each" loop of my View? Thanks.

Upvotes: 1

Views: 53

Answers (3)

Guru
Guru

Reputation: 1410

def index
  @companyaccount = Companyaccount.all
end

and in view

<% @companyaccount.each do |companyaccount| %>
 <%= companyaccount.company.name %>
<% end %>

for less db call you can change controller like

@companyaccount = Companyaccount.includes(:company).all

Upvotes: 0

IngoAlbers
IngoAlbers

Reputation: 5812

You should be able to achieve what you want with this loop:

<%= @companyaccount.each do |companyaccount| %>
  <%= companyaccount.company.name %>
  <%= companyaccount.number %>
<% end %>

Upvotes: 0

usmanali
usmanali

Reputation: 2037

You can use delegate for this.

class Companyaccount < ActiveRecord::base
  belongs_to :company
  delegate :name, to: :company, prefix: true
end

and then you can call <%= companyaccount.company_name %>

Upvotes: 1

Related Questions