在 Rails 中,如何找到 HABTM 关系中不关联的记录?
我在 Rails 中的视频和营销活动之间存在 HABTM 关系,这意味着关联存储在连接表中。我想查找所有没有关联活动的视频。做到这一点最有效的方法是什么?
谢谢您的浏览=)
I have a HABTM relationship between Videos and Campaigns in Rails which means the association is stored in a join table. I want to find all the Videos that do NOT have an associated campaign. What would be the most efficient way of doing this?
Thank you for looking =)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
:include
将对关联表进行左连接,因此任何没有营销活动的内容都应具有营销活动字段值的NULL
值。the
:include
will do a left join to the associated table so anything without a campaign should haveNULL
values for the campaign field values.Ruby 方式:
我认为如果在方法中独立使用它会更优雅。但是,我建议编写一个 命名范围 为此。话又说回来,Geoffs 版本是正确的:
此外,Geoffs 解决方案可能更有效,因为它更底层。
The Ruby way:
I think this is more elegant if you use it standalone in a method. However, I would recommend to write a named scope for that. Then again, Geoffs version is the right one:
Besides, Geoffs solution is probably more efficient as it is more lowlevel.
SQL方式:
The SQL way: