我正在使用 Ruby 2.2.1 和 Rails 4.2 构建应用程序。在我的一个 View 中,我收到了以下消息:
N+1 Query detected Politician => [:account] Add to your finder: :includes => [:account]
N+1 Query method call stack
app/models/user.rb:19:in `account'
app/controllers/home_controller.rb:6:in `index'
这是我在家庭 Controller 中的操作:
@account = current_user.account
@new_contacts = current_user.contacts.created_this_week.count
@new_collabs = current_user.collaborators.created_this_week.count
以及用户模型的相关部分:
belongs_to :role, polymorphic: true, dependent: :destroy
delegate :account, to: :role
delegate :collaborators, to: :role
delegate :contacts, to: :role
我已经尝试过以下操作:
@account = current_user.account.includes(:contacts, :collaborators)
但我只得到错误:
undefined method `includes' for <Account:0x007fa7474e04a8>
我做了一些研究,似乎只包含关系的作品(事实并非如此)。
子弹是白担心了吗?我该怎么做才能停止成为 N+1 查询?
谢谢!
最佳答案
includes
只能在 ActiveRecord::Relation
或 ActiveRecord::Base
子类、account
上调用> 似乎是模型的实例,因此不响应 ActiveRecord::Relation
方法,如 includes
。一旦您只从 current_user
获得帐户,这似乎是 bullet
的误报,尽管我不建议向协会进行延迟,但它可能会导致 N + 1 个问题在功能中。
用 AR 关联替换委托(delegate):
假设 Account
是一个常规的 ActiveRecord
模型,您可以使用 has_one
宏(查看 documentation 了解更多详细信息):
has_one :account, through: :role
当您需要遍历用户时,它非常有用:
# You can avoid `N + 1`
User.includes(:account).limit(50).each { |u| puts u.name }
关于ruby-on-rails - 对象实例的未定义方法 `includes',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30674668/