2017-02-14 52 views
0

我有这样的数据库结构:
term.rb:ActiveRecord的选择与儿童谓词

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 

我需要添加一些方法将返回接受任务没有笔记。 我该怎么做?

回答

0

试试这个:

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 
+0

太谢谢你了。你救了我的命。 – Almanack