我的问题基本上和这一个一样:
Polymorphic Association with multiple associations on the same model
Polymorphic Association with multiple associations on the same model
然而,建议/接受的解决方案不工作,稍后由评论者说明。
我有一个Photo类,用于我的应用程序。帖子可以有一张照片。但是,我想重新使用多态关系来添加辅助照片。
之前:
class Photo
belongs_to :attachable, :polymorphic => true
end
class Post
has_one :photo, :as => :attachable, :dependent => :destroy
end
所需:
class Photo
belongs_to :attachable, :polymorphic => true
end
class Post
has_one :photo, :as => :attachable, :dependent => :destroy
has_one :secondary_photo, :as => :attachable, :dependent => :destroy
end
但是,这会失败,因为它找不到类“SecondaryPhoto”。基于我可以从那个其他线程告诉我,我想要做:
has_one :secondary_photo, :as => :attachable, :class_name => "Photo", :dependent => :destroy
除非调用Post#secondary_photo只返回通过照片关联附加的相同照片,例如发布#photo === Post#secondary_photo。看看SQL,它做WHERE type =“照片”而不是,说,“SecondaryPhoto”我想…
想法?谢谢!
最佳答案
我在我的项目中做到了。
诀窍是,照片需要一个列,将用于has_one条件,以区分主要和次要照片。注意在这里的条件发生了什么。
has_one :photo, :as => 'attachable',
:conditions => {:photo_type => 'primary_photo'}, :dependent => :destroy
has_one :secondary_photo, :class_name => 'Photo', :as => 'attachable',
:conditions => {:photo_type => 'secondary_photo'}, :dependent => :destroy
这种方法的优点是,当您使用@ post.build_photo创建照片时,photo_type将自动预填充相应的类型,如’primary_photo’。 ActiveRecord是足够聪明的做到这一点。
相关文章
- ruby-on-rails - 在同一模型上具有多个关联的多态关联
- ruby-on-rails - rails 3与回形针和多个模型的多态关联
- ruby-on-rails - Rails - 与同一模型的多个关联
- ruby-on-rails-4 - 使用a有很多并且在同一个模型上有一个关联
- ruby-on-rails - Rails 4:结合has_many:通过与多态关联相关联
- ruby-on-rails - 如果多态关联的类型列不指向STI的基本模型,为什么多态关联不适用于STI?
- ruby-on-rails - 在Rails中与同一个类进行多个关联的最佳实践?
- ruby-on-rails - Ruby on Rails多态关联
转载注明原文:ruby-on-rails – Rails多态与同一模型上的多个关联关联 - 代码日志