I have a project in the works that successfully uses Paperclip and polymorphic associations. Let me show you what I have, and maybe you can apply it to your project:
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
song form and album formats include this as partial:
<div class="field"> <%= f.fields_for :artwork do |artwork_fields| %> <%= artwork_fields.label :artwork %><br /> <%= artwork_fields.file_field :artwork %> <% end %>
don't forget to include: html => {: multipart => true} with the form
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
and finally an excerpt from song_controller.rb:
def new @song = Song.new @song.build_artwork end
source share