Paperclip polymorphic styles

Hi,
I have a polymorphic Image model that I am using on 2 very different
models.
I would like to have different image styles depending on the model.

I have been searching everwhere for an answer but I haven't be able to
find something.

Does someone knows has to do that?
GReg

Greg Ma wrote in post #970946:

Hi,
I have a polymorphic Image model that I am using on 2 very different
models.
I would like to have different image styles depending on the model.

I have been searching everywhere for an answer but I haven't be able to
find something.

I assume you would need to know, for a certain "image", for which of
your 2 models this is used.

I am not familiar with Paperclip, but in general, if you use a
polymorphic asociation, it is easy to find out to which model this
"Image" object is linked to with self.association.class .

I made a little mock-up where an Image class has a polymorphic
belongs_to
association to classes "Person" and "User". What you could do is decide
based on the class of the result of the association what you are looking
at:

class Image < ActiveRecord::Base

  belongs_to :someone, :polymorphic => true

end

rails c
Loading development environment (Rails 3.0.3)
001:0> image_1 = Image.new(:url => "http://flickr…")
=> #<Image id: nil, url: "http://flickr…", someone_type: nil,
someone_id: nil, created_at: nil, updated_at: nil>
002:0> image_1.someone = User.first
=> #<User id: 1, first_name: "Jon", last_name: nil, user_name: nil,
testing: nil, created_at: "2010-12-23 21:57:01", updated_at: "2010-12-23
21:57:01">
003:0> image_1.save!
=> true
004:0> image_2 = Image.new(:url => "http://picassa…", :someone =>
Person.first)
=> #<Image id: nil, url: "http://picassa…", someone_type: "Person",
someone_id: 1, created_at: nil, updated_at: nil>
005:0> image_2.save!
=> true
006:0> Image.all
=> [#<Image id: 3, url: "http://flickr…", someone_type: "User",
someone_id: 1, created_at: "2010-12-27 20:45:01", updated_at:
"2010-12-27 20:45:01">, #<Image id: 4, url: "http://picassa…",
someone_type: "Person", someone_id: 1, created_at: "2010-12-27
20:45:36", updated_at: "2010-12-27 20:45:36">]
007:0> image_1.someone.class
=> User(id: integer, first_name: string, last_name: string, user_name:
string, testing: string, created_at: datetime, updated_at: datetime)
008:0> image_2.someone.class
=> Person(id: integer, first_name: text, last_name: text, birth_date:
date, gsm_number: text, comment: string, created_at: datetime,
updated_at: datetime)
009:0> image_1.someone.class == User
=> true
010:0> image_1.someone.class == Person
=> false

The 'image.someone.class' will tell you if this image is used for
a Person or for a User.

At a deeper level, one could also inspect the content of
image.someone_type, but I feel that is not as clean, since this
relies on the internals of a particular implementation of the
polymorphic assocation.

011:0> image_1.someone_type
=> "User"
012:0> image_2.someone_type
=> "Person"

HTH,

Peter