简体   繁体   English

Rails查询包含has_many并属于关联

[英]Rails query with includes for has_many and belongs to association

I have two model with following associations 我有以下关联的两个模型

class Application < ActiveRecord::Base
  belongs_to :registration
end

class Registration < ActiveRecord::Base
  has_many :applications, :dependent => :destroy
end

Now I am trying to do a query like this below 现在,我试图在下面做这样的查询

@applications = Application.includes(:registration).where("registration.stdniveau = ? AND uni_id = ? AND offer_sent = ? AND (offer_accepted =? OR offer_accepted =?)", 2, @uni.id, 1, nil, 1).references(:registration)

I also tried this 我也试过了

@applications = Application.includes(:registrations).where("registrations.stdniveau = ? AND uni_id = ? AND offer_sent = ? AND (offer_accepted =? OR offer_accepted =?)", 2, @uni.id, 1, nil, 1).references(:registrations)

But both query gives me unreadable error. 但是两个查询都给了我难以理解的错误。 I don't understand what am I missing here? 我不明白我在这里想念什么?

1) You should make your belongs_to singular: registration 1)您应该将自己的belongs_to设为单数: 注册

2) If you want to make a conditional selection based on another table you need to join it. 2)如果要基于另一个表进行条件选择,则需要将其联接。

3) So this should work: 3)所以这应该工作:

Application.joins(:registration)
.where("registrations.stdniveau = ? AND uni_id = ? AND offer_sent = ? AND (offer_accepted =? OR offer_accepted =?)", 2, @uni.id, 1, nil, 1")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM