【问题标题】:ActiveRecord select with predicate on childrensActiveRecord 选择与子项的谓词
【发布时间】:2017-02-14 19:56:48
【问题描述】:
我有这样的数据库结构:
术语.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
我需要添加一些方法来返回没有注释的已接受任务。
我该怎么做?
【问题讨论】:
标签:
sql
ruby-on-rails
database
activerecord
rails-activerecord
【解决方案1】:
试试这个:
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
我也将“接受的任务”查询移至范围,以使其可重复使用。
class Term < ActiveRecord::Base
has_many :tasks, through: :students
def accepted_tasks_count
tasks.accepted.count
end
end
要获取所有已接受的不带注释的任务,请使用以下命令:
Task.accepted.without_notes
要获取所有已接受的任务,而不需要特定术语的注释,请使用:
@term.tasks.accepted.without_notes