Skip to content

Instantly share code, notes, and snippets.

@stevenhaddox
Created May 29, 2009 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenhaddox/120167 to your computer and use it in GitHub Desktop.
Save stevenhaddox/120167 to your computer and use it in GitHub Desktop.
Paperclip Polymorphism Issue
paperclip steven$ script/console
Loading development environment (Rails 2.3.2)
>> p = Person.new
=> #<Person id: nil, first_name: nil, last_name: nil, design_style: nil, blog: nil, created_at: nil, updated_at: nil>
>> i = p.images.new
=> #<Image id: nil, image_attachment_type: "Person", image_attachment_id: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, created_at: nil, updated_at: nil>
>> i.image_styles
=> {:small=>"150x150>", :medium=>"300x300>", :large=>"500x500>", :thumb=>"75x75#"}
>>
class CreateImages < ActiveRecord::Migration
def self.up
create_table :images do |t|
t.string :image_attachment_type
t.integer :image_attachment_id
t.string :image_file_name
t.string :image_content_type
t.integer :image_file_size
t.timestamps
end
end
def self.down
drop_table :images
end
end
class Image < ActiveRecord::Base
# associations
belongs_to :image_attachment, :polymorphic => true
# virtual attributes
attr_accessor :image_styles
def after_initialize
self.image_styles=(set_image_styles)
# set an obvious fake to test param passing works
# self.image_styles=(set_image_styles={:thumb=>"10x10#"})
end
# paperclip
def set_image_styles(image_styles_hash=nil)
# allowing for image_styles param let's us pass a custom hash as needed
case self.image_attachment_type
when 'User'
when 'Person'
image_styles_hash ||= {
:thumb => "75x75#",
:small => "150x150>",
:medium => "300x300>",
:large => "500x500>"
}
else
image_styles_hash ||= {
:thumb => "75x75#",
:xsmall => "25x25>",
:small => "200x200>",
:medium => "500x500>",
:large => "800x800>",
:lightbox => "800x600>"
}
end
return image_styles_hash
end
# has_attached_file :image, :styles => self.image_styles, :default_style => :small
end
class Person < ActiveRecord::Base
# associations
has_many :images, :as => 'image_attachment', :dependent => :destroy
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment