我试图创建一个查看空关联的范围。
我有4个班级:User
,Idea
Project
和UserJoins
。
多个用户可以拥有相同的想法或相同的项目。
我想创建一个范围来隔离没有想法的用户。
has_many :user_joins
has_many :users, through: :user_joins
has_many :user_joins
has_many :users, through: :user_joins
has_many :user_joins
has_many :ideas, through: user_joins, source: :imaginable, source_type: 'Idea'
has_many :projects, through: user_joins, source: :imaginable, source_type: 'Project'
scope :without_ideas, ->{
# I'm stuck here.
}
belongs_to :imaginable, polymorphic: true
belongs_to :user
我正在使用Rails 3.2.17
和Ruby 2.0.0
有没有人有想法解决这个问题?
答案 0 :(得分:2)
您可以包含user_ideas
,然后检查是否为空ID。
scope :without_ideas, ->{
includes(:user_ideas).where(user_ideas: { id: nil })
}
这将离开加入user_ideas
,然后只匹配users
根本没有包含user_idea
条目(因为没有人加入)。