【问题标题】: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
    

    【讨论】:

    • 非常感谢。你救了我的命。
    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 2016-11-29
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多