我希望使用Paperclip实现多态关联,允许用户拥有一个头像和多个图片。
附件 模型:
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 %>
当我试图保存更改时,出现错误 => 未知属性:avatar。
如果我在has_one关联中删除:class_name =>'attachment',则会出现错误 => 未初始化常量User :: Avatar。
我还需要将头像附加到博客文章中,因此我需要关联成为多态(或者至少我认为如此)。
我被卡住了,任何帮助都将不胜感激。