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

时间:2017-06-16 23:29:22

标签: ruby-on-rails activerecord

我有下一个型号。它具有基于查询的属性。因为当我在我的应用程序上显示记录时,我有N + 1问题。

执行Dish.all.includes(:entries)将无效,因为此部分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

1 个答案:

答案 0 :(得分:0)

您可以添加条件的关联:

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

之后你可以这样做:

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