【问题标题】:Scope on empty association空关联的范围
【发布时间】:2025-12-31 20:10:02
【问题描述】:

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

我有 4 个课程:UserIdeaProjectUserJoins

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

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

Idea.rb

has_many :user_joins
has_many :users, through: :user_joins

项目.rb

has_many :user_joins
has_many :users, through: :user_joins

用户.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.
}

UserJoin.rb

belongs_to :imaginable, polymorphic: true
belongs_to :user

我正在使用Rails 3.2.17Ruby 2.0.0

有没有人想办法解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord scope associations


    【解决方案1】:

    您可以包含user_ideas,然后检查是否有空 id。

    scope :without_ideas, ->{
      includes(:user_ideas).where(user_ideas: { id: nil })
    }
    

    这将离开加入user_ideas,然后只匹配users,它根本没有包含user_idea 条目(因为没有一个可以加入)。

    【讨论】:

    • 谢谢,正如我在之前的评论中所说的那样,我的问题太简单了。我用多态关联编辑了我的帖子,这最终让我停下了脚步。
    • 我有类似的includes(:user_joins).where(user_joins: {imaginable_id: nil, imaginable_type: 'Idea'}),但没有想法就不可能有type。基本上,我认为与其要求Idea,不如要求not Project,但如果我在未来添加更多可想象的模型,那就不是很好了。你怎么看?提前谢谢你。