【发布时间】:2012-05-23 07:40:48
【问题描述】:
我想用回形针进行多态关联,并允许我的用户拥有一个头像和多个图像。
附件型号:
class Attachment < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
end
class Avatar < Attachment
has_attached_file :image, :styles => { :thumb => "150x150>", :view => "260x180>" },
end
class Image < Attachment
has_attached_file :image, :styles => { :thumb => "150x150>", :view => "260x180>" },
end
用户模型:
has_one :avatar, :as => :attachable, :class_name => 'Attachment', :conditions => {:type => 'avatar'}
accepts_nested_attributes_for :avatar
用户控制器:
def edit
@user.build_avatar
end
用户查看表单:
<%= form_for @user, :html => { :multipart => true } do |f| %>
<%= f.fields_for :avatar do |asset| %>
<% if asset.object.new_record? %>
<%= asset.file_field :image %>
<% end %>
<% end %>
当我尝试保存更改时出现错误 => 未知属性:头像
如果我在 has_one 关联中删除 :class_name => 'attachment' 我会收到错误 => 未初始化的常量 User::Avatar
我还需要将头像附加到博客帖子,所以我需要关联是多态的(或者至少我认为是这样)
我很困惑,任何帮助将不胜感激。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 paperclip polymorphic-associations