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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.