简体   繁体   English

自我参照关联与多态关联

[英]self referential association with polymorphic association

I have a User and Address models. 我有一个UserAddress模型。 A user may have many addresses and one as default. 用户可能有许多地址,其中一个默认地址。 I currently use this that works 我目前使用这个有效

# User.rb
belongs_to :default_address, class_name: "Address", foreign_key: :default_address_id

Now I made the Address belongs_to :addressable, polymorphic: true . 现在,我将地址belongs_to :addressable, polymorphic: true

My question is how to tell this default_address self association to use the addressable instead of going directly to the Address class 我的问题是如何告诉此default_address自我关联使用addressable而不是直接转到Address类

Solved using has_one instead of belongs_to on User.rb 使用has_one代替User.rb上的belongs_to User.rb

has_one :default_address, class_name: "Address", as: :addressable, dependent: :destroy
accepts_nested_attributes_for :default_address

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM