如何包含范围模型

时间:2018-01-17 11:26:33

标签: ruby-on-rails scope include

我们有以下模型:

class Task < ApplicationRecord
  has_many :mandatory_fields, class_name: "TaskField", foreign_key: :task_id      
end

class TaskField < ApplicationRecord
  belongs_to :task
  belongs_to :service_field

  scope :by_name, (->(name) {
   joins(:service_field).merge(ServiceField.by_name(name))
  })
end

class ServiceField < ApplicationRecord
  #with name column
  scope :by_name, ->(name) {
    where(name: name.to_sym )
  }
end

然后,我想在页面上看到每个任务的具体:mandatory_fields

Task.includes(:mandatory_fields).limit(10).map{|t| t.mandatory_fields.by_name(:check_in_confirmed)}

结果,当每个TaskField调用ServiceField时,我有N + 1。有没有办法避免那里的N + 1?

UPD:为了解决这个问题,我使用了select,但可能存在更好的解决方案?

Task.includes(:mandatory_fields => :service_field).limit(10).map{|t| t.mandatory_fields.select{|mf| mf.service_field.name == 'check_in_confirmed'}}

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

class Task < ApplicationRecord
  has_many :mandatory_fields, class_name: "TaskField", foreign_key: :task_id      
  has_many :service_fields, through: :mandatory_fields ## <-- Add this line
end

Task.includes(:service_fields).map do |task|  
  task.service_fields.by_name(:check_in_confirmed)
end