簡體   English   中英

模型具有基於查詢的屬性(N + 1)

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

我有下一個型號。 它具有基於查詢的屬性。 因為當我在我的應用程序上顯示記錄時,我有N + 1問題。

執行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

您可以添加與條件的關聯:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM