Jam*_*low 9 ruby activerecord ruby-on-rails polymorphic-associations
我对我所获得的多态关联感到有些困惑.我需要一个文章模型来获得标题图像和许多图像,但我希望有一个图像模型.更令人困惑的是,Image模型具有多态性(允许其他资源拥有许多图像).
我在我的文章模型中使用此关联:
class Article < ActiveRecord::Base
has_one :header_image, :as => :imageable
has_many :images, :as => :imageable
end
Run Code Online (Sandbox Code Playgroud)
这可能吗?谢谢.
我尝试了这个,但随后header_image返回其中一个图像.仅仅因为图像表没有指定不同的图像使用类型(header_image与普通图像).它只是说:imageable_type =两种用途的图像.因此,如果没有存储有关使用类型的信息,则ActiveRecord无法区分.
小智 4
是的。这完全有可能。
您可能需要指定 的类名header_image,因为无法推断它。也包括在内:dependent => :destroy,以确保如果文章被删除,图像也会被销毁
class Article < ActiveRecord::Base
has_one :header_image, :as => :imageable, :class_name => 'Image', :dependent => :destroy
has_many :images, :as => :imageable, :dependent => :destroy
end
Run Code Online (Sandbox Code Playgroud)
然后在另一端...
class Image < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5886 次 |
| 最近记录: |