我想与回形针建立多态关联,并允许我的用户拥有一个头像和多个图像。
附件模型:
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
用户 Controller :
def edit
@user.build_avatar
end
用户 View 表单:
<%= 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
我还需要将头像附加到博客文章中,所以我需要关联是多态的(或者至少我这么认为)
我很难过,任何帮助将不胜感激。
最佳答案
我确实有一个项目正在成功地使用 Paperclip 和多态关联。让我向您展示我所拥有的,也许您可以将其应用到您的项目中:
class Song < ActiveRecord::Base
...
has_one :artwork, :as => :artable, :dependent => :destroy
accepts_nested_attributes_for :artwork
...
end
class Album < ActiveRecord::Base
...
has_one :artwork, :as => :artable, :dependent => :destroy
accepts_nested_attributes_for :artwork
...
end
class Artwork < ActiveRecord::Base
belongs_to :artable, :polymorphic => true
attr_accessible :artwork_content_type, :artwork_file_name, :artwork_file_size, :artwork
# Paperclip
has_attached_file :artwork,
:styles => {
:small => "100",
:full => "400"
}
validates_attachment_content_type :artwork, :content_type => 'image/jpeg'
end
歌曲形式和专辑形式包括作为部分:
<div class="field">
<%= f.fields_for :artwork do |artwork_fields| %>
<%= artwork_fields.label :artwork %><br />
<%= artwork_fields.file_field :artwork %>
<% end %>
不要忘记在表单中包含 :html => { :multipart => true }
艺术品_controller.rb
class ArtworksController < ApplicationController
def create
@artwork = Artwork.new(params[:artwork])
if @artwork.save
redirect_to @artwork.artable, notice: 'Artwork was successfully created.'
else
redirect_to @artwork.artable, notice: 'An error ocurred.'
end
end
end
最后,从songs_controller.rb 摘录:
def new
@song = Song.new
@song.build_artwork
end
关于ruby-on-rails - rails 3 与回形针和多个模型的多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10606753/