本文介绍了Rails多态关联在同一模型上具有多个关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与这个问题基本相同:在同一模型上具有多个关联的多态关联

My question is essentially the same as this one:Polymorphic Association with multiple associations on the same model

但是,提议/接受的解决方案不起作用,如稍后的评论者所示.

However, the proposed/accepted solution does not work, as illustrated by a commenter later.

我在整个应用程序中都有一个Photo类.帖子可以有一张照片.但是,我想重新使用多态关系来添加辅助照片.

I have a Photo class that is used all over my app. A post can have a single photo. However, I want to re-use the polymorphic relationship to add a secondary 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".根据我可以从其他线程中分辨出的信息,我想执行以下操作:

However, this fails as it cannot find the class "SecondaryPhoto". Based on what I could tell from that other thread, I'd want to do:

   has_one :secondary_photo, :as => :attachable, :class_name => "Photo", :dependent => :destroy

除了调用Post#secondary_photo以外,它仅返回通过Photo关联附加的同一张照片,例如Post#photo === Post#secondary_photo.查看SQL,它确实在WHERE类型="Photo",而不是我想要的"SecondaryPhoto" ...

Except calling Post#secondary_photo simply returns the same photo that is attached via the Photo association, e.g. Post#photo === Post#secondary_photo. Looking at the SQL, it does WHERE type = "Photo" instead of, say, "SecondaryPhoto" as I'd like...

有什么想法吗?谢谢!

推荐答案

我已经在我的项目中做到了.

I have done that in my project.

诀窍在于,照片需要一列,该列将在has_one条件下用于区分主照片和副照片.请注意此处:conditions中发生的情况.

The trick is that photos need a column that will be used in has_one condition to distinguish between primary and secondary photos. Pay attention to what happens in :conditions here.

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足够聪明,可以做到这一点.

The beauty of this approach is that when you create photos using @post.build_photo, the photo_type will automatically be pre-populated with corresponding type, like 'primary_photo'. ActiveRecord is smart enough to do that.

这篇关于Rails多态关联在同一模型上具有多个关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:41