Rails 4可以找到沒有孩子的父母我找到了一個答案,其中有一些可用的having例子可以找到有n孩子的父母,但同樣不能用于找到沒有孩子的父母(大概是因為連接不包括他們)。scope :with_children, joins(:children).group("child_join_table.parent_id").having("count(child_join_table.parent_id) > 0")誰能指出我正確的方向?
3 回答

嗶嗶one
TA貢獻1854條經驗 獲得超8個贊
這應該做你想要的工作:
Rails 3和4
scope :without_children, includes(:children).where(:children => { :id => nil })
這里的最大區別是joins
成為a includes
:一個include加載所有關系,如果它們存在,則join將僅加載關聯的對象并忽略沒有關系的對象。
事實上,scope :with_children, joins(:children)
應該足以讓父母至少回到1個孩子。試試看!
Rails 5
請參閱下面的@ Anson的回答
正如@MauroDias所指出的,如果它是你父母和孩子之間的自我指涉關系,那么上面的代碼將不起作用。
通過一些研究,我發現了如何做到這一點:
考慮這個模型:
class Item < ActiveRecord::Base has_many :children, :class_name => 'Item', :foreign_key => 'parent_id'
如何返回沒有孩子的所有項目(ren):
Item.includes(:children).where(children_items: { id: nil })
我怎么找那張children_items
桌子的?
Item.joins(:children)
生成以下SQL:
SELECT "items".* FROM "items" INNER JOIN "items" "children_items" ON "children_items"."parent_id" = "items"."id"
所以我猜測Rails在自引用的情況下需要JOIN時使用表。

元芳怎么了
TA貢獻1798條經驗 獲得超7個贊
有一個堅實的Rails 4答案,但是對于那些來到Rails 5的人來說,你有更多的選擇。
使用Rails 5:
從Rails 5開始,您還可以使用left_outer_joins來避免加載關聯。它是在拉取請求#12071中引入的。
scope :without_children, left_outer_joins(:children).where(children: { id: nil })
對于有孩子的父母,MrYoshiji的Rails 4解決方案仍然可以使用:
scope :with_children, joins(:children)

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
這就是我為Rails 5解決它的方法:
scope :without_comments, -> do left_outer_joins(:comments).where(comments: { id: nil })end
- 3 回答
- 0 關注
- 554 瀏覽
添加回答
舉報
0/150
提交
取消