Rails 3与2个表之间的连接

时间:2011-06-12 10:43:53

标签: mysql ruby-on-rails-3 join view

我有2个型号,汽车注册

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

在CarsController中:

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

在视图中:

<% @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 %>

这是我对汽车的陈述。我正在尝试打印每个车主的电子邮件。电子邮件位于表格注册(模型注册)中。我不知道如何对数据库进行查询,我想从表注册中获取电子邮件,表格中的列registration_id 汽车 == id表格注册列...

所以我想问你,如果你有小费,怎么做......

2 个答案:

答案 0 :(得分:1)

使用此功能来获取电子邮件:

<%= car.registration.email %>

如果您想要预先加载,请改用控制器中的以下行:

@cars = Car.includes(:registration)

不需要@cars2

答案 1 :(得分:1)

你有大写字母的联想。它应该像这样小

class Car < ActiveRecord::Base
  belongs_to :registration
end

此外,您不必在控制器中分配2个变量

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

并在视图中

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