Reputation: 1054
I have four models : User, Product, Ownership, and Location. Product belongs to User through Ownership and User has many Products through Ownership. When a User create a Product, I want that if the User has a Location, the Product is linked to the same Location. So here is my question :
Can we transform this :
class Location < ActiveRecord::Base
belongs_to :localizable, polymorphic: true
end
class User < ActiveRecord::Base
has_one :location, as: :localizable
end
class Product < ActiveRecord::Base
has_one :location, as: :localizable
end
into this :
class Location < ActiveRecord::Base
has_many :localizables, polymorphic: true
end
class User < ActiveRecord::Base
belongs_to :location, as: :localizable
end
class Product < ActiveRecord::Base
belongs_to :location, as: :localizable
end
Upvotes: 1
Views: 1161
Reputation: 15515
How about delegating product.location
to product.owner.location
.
This can be done in the Product class as follows (change identifier for the owner/user relation as needed):
class Product < ActiveRecord::Base
delegate :location, to: :owner
end
If you call product.location
, the location of the owner will be returned.
Upvotes: 1