【问题标题】:Select all records that are not associated with other选择所有与其他不相关的记录
【发布时间】:2014-08-19 21:06:18
【问题描述】:

我有两张桌子pagesmenu_itemspages 有很多menu_itemsmenu_items 属于pages。在 Rail 4 中,如何仅选择那些未与 menu_items 链接的 pages

提前致谢!

【问题讨论】:

  • 哇,抱歉,忘记了这个问题。

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

以下每一项都应该有效:

Page.includes(:menu_items).where( menu_items: { page_id: nil} )

Page.find(:all, conditions: { :menu_items.count: 0 } )

Page.where('id NOT IN (SELECT DISTINCT(page_id) FROM menu_items)')

【讨论】:

    【解决方案2】:

    也许Page.where 就是您要找的东西。实际上,where 方法调用通过Page 数据库搜索指定类型的所有对象。通过将菜单的 id 参数设为 nil 来调用它,您将搜索所有没有菜单 id 的页面。

    理想情况下,您想致电Page.where(page.menu_items.empty?),当然,这是不允许的。

    环顾this question 和你的差不多。他们通过以下方式解决它:

    Page.includes(:menu_items).where( :menu_items => {:page_id=>nil} )
    

    【讨论】:

    • pages 表中没有menu_items_id 列。
    猜你喜欢
    • 2015-06-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 2015-06-18
    • 1970-01-01
    • 2018-01-07
    • 2018-03-18
    相关资源
    最近更新 更多