在 Rails 中,如何找到 HABTM 关系中不关联的记录?

发布于 2024-09-09 18:58:07 字数 101 浏览 7 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

平生欢 2024-09-16 18:58:07
Video.all(:include => :campaigns, :conditions => ["campaigns.id IS ?", nil])

:include 将对关联表进行左连接,因此任何没有营销活动的内容都应具有营销活动字段值的 NULL 值。

Video.all(:include => :campaigns, :conditions => ["campaigns.id IS ?", nil])

the :include will do a left join to the associated table so anything without a campaign should have NULL values for the campaign field values.

魂归处 2024-09-16 18:58:07

Ruby 方式:

Video.all.select {|v| v.campaigns.empty?}

我认为如果在方法中独立使用它会更优雅。但是,我建议编写一个 命名范围 为此。话又说回来,Geoffs 版本是正确的:

named_scope :campaign_less, :include => :campaigns, :conditions => ["campaigns.id IS ?", nil]

此外,Geoffs 解决方案可能更有效,因为它更底层。

The Ruby way:

Video.all.select {|v| v.campaigns.empty?}

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:

named_scope :campaign_less, :include => :campaigns, :conditions => ["campaigns.id IS ?", nil]

Besides, Geoffs solution is probably more efficient as it is more lowlevel.

执着的年纪 2024-09-16 18:58:07

SQL方式:

Videos.select_by_sql("SELECT * FROM videos WHERE id NOT IN (SELECT video_id FROM campaign_videos)")

The SQL way:

Videos.select_by_sql("SELECT * FROM videos WHERE id NOT IN (SELECT video_id FROM campaign_videos)")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文