我有一个简单的关联,例如:
class User < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :user
# Photo fields => id, image, photo_type
end
在照片模型photo_type
中值可以在"个人","家庭"或"官方"中。
让所有用户都没有照片或photo_type!='个人'的最佳方法是什么(如果用户有照片(?
我感谢任何帮助。谢谢!
我已经标记了一个具有很多答案的副本,但简而言之,您可以使用:
# No photos
User.includes(:photos).where( photos: { user_id: nil } )
# Not personal
User.includes(:photos).where.not( photos: { photo_type: "personal" } )
# Users with photos, where the `photo_type` isn't "personal"
User.includes(:photos).where.not( photos: { user_id: nil, photo_type: "personal" } )
还有一种Rails 5方法可以避免加载关联,尽管我还没有亲自使用:
User.left_outer_joins(:photos).where.not( photos: { user_id: nil, photo_type: "personal" } )
看起来如何?最后一个选项要做您追求的事情?
让我知道您是否有任何问题。