user1946705 user1946705 - 1 month ago 7
MySQL Question

Rails 3 with joins among 2 tables

I have 2 models, car and registrations.

class Car < ActiveRecord::Base
belongs_to :Registration
end

class Registration < ActiveRecord::Base
has_many :cars, :dependent => :destroy
accepts_nested_attributes_for :cars, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end


In CarsController:

def index
@cars = Car.all
@cars2 = Car.all(:joins => :Registration)
end


In view:

<% @cars.each do |car| %>
<tr>
<td><%= car.twitter %></td>
<td><%= car.facebook %></td>
<td>
<% @cars2.Registration.each do |h| %> #here is my problem
<%= h.email %>
<% end %>
</td>
</tr>
<% end %>


This is my statement of cars. I am trying to print for every car owner's email. The email is in table Registration (model registration). I don't know how to make a query to database, that I want to get email from table Registrations, when column registration_id in table Cars == id column of table Registrations...

So I would like to ask you, if you have a tip, how to do...

Answer

You have got your associations in capital letters. It should be in small like this

class Car < ActiveRecord::Base
  belongs_to :registration
end

Also you dont have to assign 2 variables in the controller

def index
  @cars = Car.includes(:registration)
end

and in the view

<% @cars.each do |car| %>
  <tr>
    <td><%= car.twitter %></td>
    <td><%= car.facebook %></td>
    <td>
      <%= car.registration.email %> #here is my problem
    </td>
  </tr>
<% end %>