当要包含的模型不直接与基本模型关联时,如何调用 include(left join) ?
我想加入三种模式:预订、转预订和客户。一个预订有多个子预订,一个预订也属于(也可能不属于)客户。我想列出按 client.name 订购的所有 sub_bookings。我需要加入预订和子挂钩,以及预订和客户之间的包含关系。我尝试了以下方法,但没有成功。
SubBooking.joins(:booking).includes(:booking=>:client).order('client.name')
模型如下
class Booking < ActiveRecord::Base
belongs_to :client
has_many :sub_bookings
...
end
class SubBooking < ActiveRecord::Base
belongs_to :booking
...
end
class Client < ActiveRecord::Base
has_many :bookings
...
end
更准确地说,我想要生成的 SQL 是这样的
SELECT * FROM sub_bookings
INNER JOIN bookings ON bookings.id = sub_bookings.booking_id
LEFT JOIN Clients ON bookings.client_id = clients.id
ORDER BY client.name
There are three models that i want to join, booking, subbooking and client. A booking has_many sub_bookings also a booking belongs to(also may not) a client. I want to list all the sub_bookings ordered by the client.name. I need a join on booking and subhooking and an include relationship between booking and client. I tried the following and it didnt work.
SubBooking.joins(:booking).includes(:booking=>:client).order('client.name')
The models are as follows
class Booking < ActiveRecord::Base
belongs_to :client
has_many :sub_bookings
...
end
class SubBooking < ActiveRecord::Base
belongs_to :booking
...
end
class Client < ActiveRecord::Base
has_many :bookings
...
end
To be more precise the SQL I want to be generated is something like this
SELECT * FROM sub_bookings
INNER JOIN bookings ON bookings.id = sub_bookings.booking_id
LEFT JOIN Clients ON bookings.client_id = clients.id
ORDER BY client.name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你的代码中有一个拼写错误。我已经创建了您在问题中描述的应用程序,并尝试了一些简单的查询。接下来,我尝试了下面输出中第一行中看到的示例查询。
正如您所看到的,它抛出了一个很好的错误,这就是您可能已经看到的,只需更正此调用:
到此:
即可解决该错误。
如果您想查看我在 GitHub 上使用的代码。如果您还有其他问题,请告诉我。
问候,
德文·M
I think you have a typo in your code. I have created the application you described in your question and tried a few simple queries. Next I tried your sample query seen on line one in the output below.
As you see it throws a nice error which is what you may have seen, simply correcting the call from this:
To this:
resolves the error.
If you would like to see the code I used its on GitHub over here. Let me know if you have any more questions.
Regards,
Devin M