我的问题基本上和这个一样:

然而,正如后面的一位 comments 者所说明的,提议/接受的解决方案不起作用.

我有一个照片类,它在我的应用程序中随处可见.一篇帖子可以有一张照片.然而,我想重新使用多态关系来添加第二张照片.

之前:

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只返回通过照片关联附加的相同照片,例如Post#photo==Post#secondary _photo.看看SQL,它会在WHERE type="Photo"中执行,而不是像我希望的那样,比如说"SecondaryPhoto"...

思想?谢谢

推荐答案

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

诀窍在于,照片需要一个列,该列将用于区分主要照片和次要照片.注意这里:conditions人的情况.

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创建照片时,照片类型将自动预填充相应的类型,如"primary_photo".ActiveRecord足够聪明,可以做到这一点.

Ruby-on-rails相关问答推荐

如何使用 activerecord activerecord-session_store 在 Rails 应用程序中使用 cookie 值在数据库中查找会话记录

ViewModel 和 Controller 有什么区别?

Rails ActiveRecord 中的更新插入

比较 Rails 中的日期

如何使用 Rails 3 / Rack 在没有 www 的情况下重定向?

在 Nokogiri 中获取属性值以提取链接 URL

如何在 Linux 上使用 Ruby 2.0 改进独角兽进程之间的内存共享

没有图像时如何在回形针中显示隐藏图像

在 where 查询中查找 nil has_one 关联

在 factory_girl 中填充与 children 的关联

Elastic Beanstalk Ruby/Rails 需要安装 git,所以 bundle install 可以工作.. 但不是

Rails - 具有空数组的强参数

rails 4 before_validation on: :create 或 on: :save

Rails:进行不可逆转的迁移是不是很糟糕?

登录delay_job?

将 Rails 服务器绑定到 0.0.0.0 能给你带来什么?

如何跳过失败的迁移? (耙分贝:迁移)

Ruby 中有与 slice 函数相反的函数吗?

在 Rails 4.1 中,如何通过枚举符号查找记录?

为什么 rails bootstrap 这么慢,我该怎么办?