简体   繁体   English

模型具有基于查询的属性(N + 1)

[英]Model has a attribute based on a query (N+1)

I have the next model. 我有下一个型号。 It has an attribute base on a query. 它具有基于查询的属性。 Because that attribute I have the N+1 problem when I show the record on my application. 因为当我在我的应用程序上显示记录时,我有N + 1问题。

Doing Dish.all.includes(:entries) will not work because this section from_today.from_current_time of the query. 执行Dish.all.includes(:entries)将无法正常工作,因为此部分from_today.from_current_time查询的from_today.from_current_time

class Dish < ApplicationRecord
  has_many :entries, dependent: :destroy

  belongs_to :user
  belongs_to :category

  before_validation :init, on: :create

  def available?
   current_entry = entries.from_today.from_current_time
   return false if current_entry.count.zero?
   current_entry.first.dishes_left.positive?
  end

end

You may add an association with an condition: 您可以添加与条件的关联:

class Dish < ApplicationRecord
  has_many :entries
  has_many :entries_from_today,
    -> { merge(Entry.from_today) },
    class_name: 'Entry'

After that you may do like this: 之后你可能会这样:

dishes = Dish.all.includes(:entries_from_today)
dishes.each do |dish|
  puts dish.entries_from_today
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM