【问题标题】:How to include the scoped model如何包含范围模型
【发布时间】:2018-06-26 06:28:04
【问题描述】:

让我们有以下模型:

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)}

结果我有 N+1,当每个 TaskField 调用 ServiceField。有没有办法避免 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'}}

【问题讨论】:

  • 如何使用 AR 选择以及在哪里? Task.includes(:mandatory_fields =&gt; :service_field).select('service_field.name').where(service_field: { name: 'check_in_confirmed' }).limit(10).
  • @SebastianPalma,谢谢。但这并不能在全球范围内解决任务。我不仅需要service_filed.name,还需要几乎所有的专栏。

标签: ruby-on-rails scope include


【解决方案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

【讨论】:

  • 谢谢!这是一般的工作技术。对于我的情况,我需要遍历mandatory_fields(不是service_fields) 应该由相关service_field 选择。
猜你喜欢
  • 2020-08-24
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多