rails 3与回形针和多个模型的多态关联

kai*_*gth 7 ruby-on-rails paperclip polymorphic-associations ruby-on-rails-3

我想与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
Run Code Online (Sandbox Code Playgroud)

用户模型:

has_one :avatar, :as => :attachable, :class_name => 'Attachment', :conditions => {:type => 'avatar'}
accepts_nested_attributes_for :avatar
Run Code Online (Sandbox Code Playgroud)

用户控制器:

def edit
   @user.build_avatar
end
Run Code Online (Sandbox Code Playgroud)

用户视图表单:

<%= 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 %>
Run Code Online (Sandbox Code Playgroud)

当我尝试保存更改时,我得到错误=>未知属性:头像

如果我删除has_one关联中的:class_name =>'attachment',我会得到错误=> uninitialized constant User :: Avatar

我还需要将头像附加到博客帖子,所以我需要关联是多态的(或至少我认为如此)

我很难过,任何帮助都将不胜感激.

Bre*_*ett 7

我确实有一个项目正在成功使用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
Run Code Online (Sandbox Code Playgroud)

歌曲形式和专辑形式包括这个部分:

<div class="field">
<%= f.fields_for :artwork do |artwork_fields| %>
  <%= artwork_fields.label :artwork %><br />
  <%= artwork_fields.file_field :artwork %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

不要忘记在表单中包含:html => {:multipart => true}

artworks_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
Run Code Online (Sandbox Code Playgroud)

最后,来自songs_controller.rb的摘录:

def new
    @song = Song.new
    @song.build_artwork
end
Run Code Online (Sandbox Code Playgroud)