[英]Is it possible to inverse polymorphic association?
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
. 如何委托
product.location
到product.owner.location
。
This can be done in the Product class as follows (change identifier for the owner/user relation as needed): 可以在Product类中完成以下操作(根据需要更改所有者/用户关系的标识符):
class Product < ActiveRecord::Base
delegate :location, to: :owner
end
If you call product.location
, the location of the owner will be returned. 如果您致电
product.location
,将返回所有者的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.