brc*_*ebn 3 ruby activerecord scope ruby-on-rails associations
我正在尝试创建一个查看空关联的范围。
我有 4 节课:User、Idea Project和UserJoins。
多个用户可以有相同的想法或相同的项目。
我想创建一个范围来隔离没有想法的用户。
has_many :user_joins
has_many :users, through: :user_joins
Run Code Online (Sandbox Code Playgroud)
has_many :user_joins
has_many :users, through: :user_joins
Run Code Online (Sandbox Code Playgroud)
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)
belongs_to :imaginable, polymorphic: true
belongs_to :user
Run Code Online (Sandbox Code Playgroud)
我正在使用Rails 3.2.17和Ruby 2.0.0
有人有办法解决这个问题吗?
您可以包含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条目的条目(因为没有条目可加入)。
| 归档时间: |
|
| 查看次数: |
1315 次 |
| 最近记录: |