所属的Rails包含未识别的二阶关联

时间:2018-10-27 13:49:08

标签: ruby-on-rails activerecord

我在Rails应用程序中有3个嵌套模型:

class User < ApplicationRecord
  has_many :products, dependent: :destroy
end

class Product < ApplicationRecord
  belongs_to :user
  has_one :insurance_policy
end

class InsurancePolicy < ApplicationRecord
  belongs_to :product, -> { includes :user }
end

我试图避免这样做:

InsurancePolicy.last.product.user

使用includes_to方法的include附加内容,我得到以下错误消息:

[10] pry(main)> InsurancePolicy.last.user
  InsurancePolicy Load (0.4ms)  SELECT  "insurance_policies".* FROM "insurance_policies" ORDER BY "insurance_policies"."id" DESC LIMIT $1  [["LIMIT", 1]]
NoMethodError: undefined method `user' for #<InsurancePolicy:0x00007fc50a2d5a10>
from /Users/albert/.rbenv/versions/2.4.4/lib/ruby/gems/2.4.0/gems/activemodel-5.2.0/lib/active_model/attribute_methods.rb:430:in `method_missing'

为什么缺少该方法?我需要在我的insurance_policies表中添加一列user_id吗?

我正在遵循AR的官方文档。

class LineItem < ApplicationRecord
  belongs_to :book, -> { includes :author }
end

class Book < ApplicationRecord
  belongs_to :author
  has_many :line_items
end

class Author < ApplicationRecord
  has_many :books
end

这是我所缺少的吗?我不太了解:

If you use the select method on a belongs_to association, you should also set the :foreign_key option to guarantee the correct results.

1 个答案:

答案 0 :(得分:0)

调用InsurancePolicy.last.user是错误的,因为InsurancePolicy模型与User模型没有关联。

关联belongs_to :product, -> { includes :user }也是不正确的,因为模型ProductUser模型没有关联。为了使includes正常工作,您需要将其添加到Product

belongs_to :user

之后InsurancePolicy.last.product.user应该可以工作。

更新

没有belongs_to through关联,您可以用来直接从User访问InsurancePolicy模型。要使InsurancePolicy.last.user工作,只需将该关联定义为InsurancePolicy的方法:

def user
  product.user
end