Reputation: 31
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. 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:
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. 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.
As far as I understand this happens, because a model is saving only one polymorphic id instead of multiple.
My question is how such associations should be handled properly? I think this is pretty common problem in web development?!
Upvotes: 3
Views: 317
Reputation: 1097
I think in your user model you should use 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.
Upvotes: 1