【问题标题】:Rails 3 with joins among 2 tablesRails 3 与 2 个表之间的连接
【发布时间】:2011-06-12 10:43:52
【问题描述】:

我有 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(模型注册) 中。我不知道如何查询数据库,我想从表 Registrations 中获取电子邮件,当表 Cars 中的列 registration_id == 表 Registrations 的 id 列时...

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

【问题讨论】:

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


    【解决方案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 %>
    

    【讨论】:

      【解决方案2】:

      使用它来获取电子邮件:

      <%= car.registration.email %>
      

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

      @cars = Car.includes(:registration)
      

      不需要@cars2

      【讨论】:

      • 我尝试使用,但出现错误:“undefined method `registration' for ...” 我不知道为什么会出现此错误,关联看起来不错(我认为)
      猜你喜欢
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 2014-07-18
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多