2017-02-14 129 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