2016-09-28 71 views

回答

0

我要選擇有沒有圖像

你接近你的where.not事情的所有帖子。

這裏是實現它傳統的方式:

Post.includes(:images).where(images: { id: nil }) 
+0

我認爲這仍然會運行'n + 1'查詢? –

+0

它沒有運行n + 1,只是不工作。你測試過了嗎? –

+0

@BartekGładys我希望你在這裏留下你的評論,讓** Rails的每個人都能看到它;)但那很好,隨着時間的推移,你也會更好地學習它。直到那時你可以自由地對完全有效的答案付諸表決,在我身邊沒有任何違法行爲。 –

0

我認爲你可以達到你想要的東西如下:

Post.includes(:images).where.not(id: Image.pluck(:post_id).uniq) 

如果你想include與條件的關聯中,你需要創建條件的新的關聯。

喜歡的東西:

# app/models/user.rb 
class User < ActiveRecord::Base 
    has_many :posts, dependent: :destroy 
    has_many :published_posts, -> { published }, class_name: 'Post' 
end 

# app/models/post.rb 
class Post < ActiveRecord::Base 
    belongs_to :user 
    scope :published, -> { where(published: true) } 
end 
+0

這是錯誤的在某種意義上,它會返回所有帖子與**圖像,我想你的意思是使用'where.not(id:Image.pluck(:post_id).uniq)':) –

+0

ahh ..謝謝更新 –

0

includes

Post.includes(:images).reject{ |p| p.images.any? } 

注意,這將首先獲取所有帖子,然後遍歷他們試試這個。它不是數據庫爲你做的主要工作,相反,ruby/activerecord爲每個帖子創建一個對象,然後查詢帖子。

+0

處理db與紅寶石 - 不好;) –

+0

嗨,我編輯你的問題,爲什麼這不是首選的方法(主要工作應該由數據庫完成)。你好我的downvote被撤銷了。不要拿它親自,它是一個有效的答案,但不是很好的做法。 – Felix