Igo*_*ues 11 ruby performance activerecord ruby-on-rails ruby-on-rails-4
我正在使用Ruby 2.2.1和Rails 4.2来构建应用程序.在我的一个观点中,我收到以下消息:
检测到N + 1查询Politician => [:account]添加到您的finder :: includes => [:account]
N + 1查询方法调用堆栈
app/models/user.rb:19:在`account'中
app/controllers/home_controller.rb:6:在'index'中
这是我在家控制器上的动作:
@account = current_user.account
@new_contacts = current_user.contacts.created_this_week.count
@new_collabs = current_user.collaborators.created_this_week.count
Run Code Online (Sandbox Code Playgroud)
以及用户模型的相关部分:
belongs_to :role, polymorphic: true, dependent: :destroy
delegate :account, to: :role
delegate :collaborators, to: :role
delegate :contacts, to: :role
Run Code Online (Sandbox Code Playgroud)
我已经尝试过以下方法:
@account = current_user.account.includes(:contacts, :collaborators)
Run Code Online (Sandbox Code Playgroud)
但我只得到错误:
undefined method `includes' for <Account:0x007fa7474e04a8>
Run Code Online (Sandbox Code Playgroud)
我做了一些研究,看起来似乎只包括关系的作品(事实并非如此).
子弹无所畏惧吗?我该怎么做才能停止成为N + 1查询?
谢谢!
includes只能在ActiveRecord::Relations或ActiveRecord::Base子类上调用,account似乎是模型的一个实例,因此不会对ActiveRecord::Relation方法做出响应includes.bullet一旦你只是来自帐户current_user,这似乎是误报,虽然我不建议对关联的爆燃,但它可能导致功能中的N + 1问题.
用AR关联代替delagate:
假设这Account是一个常规ActiveRecord模型,您可以使用has_one宏(查看文档以获取更多详细信息):
has_one :account, through: :role
Run Code Online (Sandbox Code Playgroud)
当您需要遍历用户时,它非常少:
# You can avoid `N + 1`
User.includes(:account).limit(50).each { |u| puts u.name }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8007 次 |
| 最近记录: |