以下是关于多态性的Rails指南示例中的模型/关系:
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
在我的情况下,Product
有很多Pictures
是可以的,但我不希望Employee
拥有多个Picture
。我希望Employee
模型为:
class Employee < ActiveRecord::Base
has_one :picture, :as => :imageable
end
这将允许我使用@employee.picture
而不是@employee.pictures.first
(使用@ employee.pictures.first只是有点臭味 - 不代表关系的真实意图。 )
rails是否支持has_one ____ :as => :imageable
关系?
答案 0 :(得分:0)
首先,您必须创建一个连接表(类似于图片)。然后你将有下一个图片模型:
class Picture < ActiveRecord::Base
has_many :picturing, :dependent => :destroy
end
class Picturing < ActiveRecord::Base
belongs_to :picture
belongs_to :picturable, polymorphic: true
end
产品型号:
class Product < ActiveRecord::Base
# Many pictures
has_many :picturing, as: :picturable
end
员工模式:
class Employee < ActiveRecord::Base
has_one :picturing, as: :picturable
has_one :picture, through: :picturing
end