简体   繁体   中英

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.

Doing Dish.all.includes(:entries) will not work because this section from_today.from_current_time of the query.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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