2
我使用bullet gem讓我知道N + 1個查詢。如何隨時加入一個模型以加載熱心
我想避免添加包括零星。
我有屬於user
模型
有沒有辦法告訴隨時隨地評論模型被訪問到包括用戶,以及模型中的comment
模式? (而不是做Comment.include(:user)
每次)
我使用bullet gem讓我知道N + 1個查詢。如何隨時加入一個模型以加載熱心
我想避免添加包括零星。
我有屬於user
模型
有沒有辦法告訴隨時隨地評論模型被訪問到包括用戶,以及模型中的comment
模式? (而不是做Comment.include(:user)
每次)
您可以使用default_scope
:
class Comment < ActiveRecord::Base
default_scope includes(:user)
end
Comment.first # => the same as Comment.includes(:user).first
你應該做
class Comment < ActiveRecord::Base
default_scope { includes(:user) }
end
謝謝,我該如何使用與'default_scope:爲了=> 'created_at DESC' '? –
嘗試'default_scope包括(:user).order(「created_at desc」)'。 – kulesa