Rails 多态关联在同一模型上具有多个关联 [英] Rails Polymorphic Association with multiple associations on the same model

查看:24
本文介绍了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 外,只返回通过照片关联附加的相同照片,例如发布#照片 === 发布#secondary_photo.查看 SQL,它确实 WHERE type = "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 多态关联在同一模型上具有多个关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆