空关联的范围

brc*_*ebn 3 ruby activerecord scope ruby-on-rails associations

我正在尝试创建一个查看空关联的范围。

我有 4 节课:UserIdea ProjectUserJoins

多个用户可以有相同的想法或相同的项目。

我想创建一个范围来隔离没有想法的用户。

想法.rb

has_many :user_joins
has_many :users, through: :user_joins
Run Code Online (Sandbox Code Playgroud)

项目.rb

has_many :user_joins
has_many :users, through: :user_joins
Run Code Online (Sandbox Code Playgroud)

用户.rb

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.
}
Run Code Online (Sandbox Code Playgroud)

用户加入.rb

belongs_to :imaginable, polymorphic: true
belongs_to :user
Run Code Online (Sandbox Code Playgroud)

我正在使用Rails 3.2.17Ruby 2.0.0

有人有办法解决这个问题吗?

Sha*_*ell 5

您可以包含user_ideas并检查 id 是否为空。

scope :without_ideas, ->{
  includes(:user_ideas).where(user_ideas: { id: nil })
}
Run Code Online (Sandbox Code Playgroud)

这将离开连接user_ideas,然后仅匹配根本users不包含user_idea条目的条目(因为没有条目可加入)。