ruby-on-rails - 对象实例的未定义​​方法 `includes'

标签 ruby-on-rails ruby performance ruby-on-rails-4 activerecord

我正在使用 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::RelationActiveRecord::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/

相关文章:

ruby-on-rails - Rails 不会为主键使用序列?

ruby-on-rails - Haml 嵌套与 Rails 中渲染的部分

ruby-on-rails - 如何在谷歌地图中制作半径圆?

ruby-on-rails - 在 Rails 中重构相同的模型

ruby-on-rails - Windows 7 上的 Docker Compose : Could not locate Gemfile or . bundle /目录

java - 完成一个功能;返回无效或中断循环?

ruby-on-rails - 如何使用 angularjs 和 rails/devise 更新密码?

Ruby 正则表达式匹配多次

c - SpMV 算法的大小与时间图中的不规则时间跳跃

php - php中的继承速度