简体   繁体   English

Rails与使用它的多个属性进行多态关联

[英]Rails polymorphic association with multiple attributes using it

I have Address class which I need to use in multiple other models and in some models I need to use it for multiple attributes. 我有一个我需要在其他多个模型中使用的Address类,在某些模型中我需要将它用于多个属性。 The setup I made so far: 我到目前为止的设置:

class User
  has_one :pickup_address,   class_name: 'Address', as: :location, dependent: :destroy
  has_one :delivery_address, class_name: 'Address', as: :location, dependent: :destroy   
end

class Address
  belongs_to :location, polymorphic: true
end

The Address class will also be used in other models later, like: Address类也将在以后的其他模型中使用,例如:

class ServiceProvider
  has_one :address, as: :location
end

The Problem I have now is with class User, as it has multiple attributes using the same polymorphic Address model. 我现在遇到的问题是类User,因为它有多个使用相同多态地址模型的属性。 When building model it allows to set up both pickup and delivery addresses, but after saving, when I'm trying to fetch it from db, both fields have the same (latter) address object which was intended for delivery_address. 在构建模型时,它允许设置拾取和传递地址,但在保存之后,当我尝试从db获取它时,两个字段都具有相同的(后一个)地址对象,该对象用于delivery_address。

As far as I understand this happens, because a model is saving only one polymorphic id instead of multiple. 据我所知,这种情况发生了,因为模型只保存了一个多态id而不是多个。

My question is how such associations should be handled properly? 我的问题是如何正确处理这种关联? I think this is pretty common problem in web development?! 我认为这是Web开发中非常常见的问题?!

I think in your user model you should use belongs_to : 我认为在你的用户模型中你应该使用belongs_to

belongs_to :pickup_address, :class_name => "Address", :foreign_key => "pickup_address_id"
belongs_to :delivery_address, :class_name => "Address", :foreign_key => "delivery_address_id"

It means, that id's of addresses will be stored in users table. 这意味着,地址的id将存储在users表中。

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

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