我在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.
答案 0 :(得分:0)
调用InsurancePolicy.last.user
是错误的,因为InsurancePolicy
模型与User
模型没有关联。
关联belongs_to :product, -> { includes :user }
也是不正确的,因为模型Product
与User
模型没有关联。为了使includes
正常工作,您需要将其添加到Product
:
belongs_to :user
之后InsurancePolicy.last.product.user
应该可以工作。
更新:
没有belongs_to through
关联,您可以用来直接从User
访问InsurancePolicy
模型。要使InsurancePolicy.last.user
工作,只需将该关联定义为InsurancePolicy
的方法:
def user
product.user
end