Sql ActiveRecord在子对象上使用谓词选择
我有这样的数据库结构:Sql ActiveRecord在子对象上使用谓词选择,sql,ruby-on-rails,database,activerecord,rails-activerecord,Sql,Ruby On Rails,Database,Activerecord,Rails Activerecord,我有这样的数据库结构: term.rb: class Term < ActiveRecord::Base has_many :tasks, through: :students ... def accepted_tasks_count tasks.where(status: Task.statuses[:accepted]).count end 类术语
term.rb:
class Term < ActiveRecord::Base
has_many :tasks, through: :students
...
def accepted_tasks_count
tasks.where(status: Task.statuses[:accepted]).count
end
类术语
task.rb:
class Task < ActiveRecord::Base
has_many :notes, through: :submissions
...
def notes_count
self.notes.count
end
类任务
我需要添加一些方法,它将返回没有注释的已接受任务。
我该怎么做呢?试试这个:
class Task < ActiveRecord::Base
has_many :notes, through: :submissions
scope :accepted, -> { where(status: self.statuses[:accepted]) }
scope :without_notes, -> { includes(:notes).where(notes: { id: nil }) }
end
要获取所有接受的任务,但不包含特定术语的注释,请使用:
@term.tasks.accepted.without_notes
非常感谢你。你救了我的命。
Task.accepted.without_notes
@term.tasks.accepted.without_notes