我正在使用Ruby 2.2.1和Rails 4.2来构建应用程序。在我的一种观点中,我收到以下消息:



这是我在家庭 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查询?

谢谢!

最佳答案

只能在includesActiveRecord::Relation子类上调用ActiveRecord::Baseaccount似乎是模型的实例,因此无法响应ActiveRecord::Relation这样的includes方法。一旦您仅从bullet获得帐户,就对current_user似乎是错误的肯定,尽管我不建议对关联进行延迟,但这可能导致功能中出现N + 1个问题。

用AR关联替换滞后物:

假设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/

10-13 07:37
查看更多