关于 Rails 关联的问题,其中 has_one
关联与两个可能的模型之一相关。就像多态关联一样,但反过来。
所以我有两种不同类型的银行账户,都属于UserConfig
:
class SwedishBankAccount
belongs_to :user_config
end
class ForeignBankAccount
belongs_to :user_config
end
问题是如何在我的UserConfig
中管理它。它应该与 SwedishBankAccount
或 ForeignBankAccount
关联,但不能同时与两者关联。
最佳答案
您可以使用多态关系。在 UserConfig
模型中添加 target_id
和 target_type
列
class UserConfig < ActiveRecord::Base
belongs_to :target, :polymorphic => true
end
然后您只需使用模型 SwedishBankAccount
As
class SwedishBankAccount < ActiveRecord::Base
has_one :user_config, :as => :target
end
在模型ForeignBankAccount
中为
class ForeignBankAccount < ActiveRecord::Base
has_one :user_config, :as => :target
end
关于ruby-on-rails - Rails - has_one 与两个可能模型之一的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36172620/