2017-06-16 15 views
1

私は次のモデルを持っています。これは、クエリの属性ベースを持ちます。その属性のため、アプリケーションにレコードを表示するとN + 1の問題が発生します。モデルにはクエリ(N + 1)に基づく属性があります

Doing 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 

答えて

0

:私は渡す必要がある場合

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

答えてくれてありがとう、と何:その後

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

を、あなたは次のように行うことができます引数? –

+0

@CarlosGuerrero、Railsはconditionとの関係を事前にロードすることはできません。必要に応じて手動でプリロードする必要があります。 –

関連する問題