Rails多态关系 - 需要同时使用has_many和has_one

时间:2014-01-11 23:52:54

标签: ruby-on-rails-3 activerecord polymorphism

以下是关于多态性的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关系?

1 个答案:

答案 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