Basically I have an Image
model which polymorphically belongs to imageable
which are by far List
and Item
. Since an image will have its own attribute and relationship, I don't want to treat images like attributes of the List
and Item
and mess it up. So I create the Image
model.
What I want to achieve is that List
should have a logo thumb image where height equals width but Item
has a different style. Paperclip doc has told us to create dynamic styles using lambda
. So here's my Image
model:
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
has_attached_file :file,
:styles => lambda { |file| { thumb: (file.instance.imageable_type == "List") ? "300x300!" : "200x100!") } }
:default_url => "/images/:style/missing.png"
end
And my List
model:
class List < ActiveRecord::Base
def list_params
params.require(:list).permit(:title, :image_attributes)
end
has_one :image, as: :imageable
accepts_nested_attributes_for :image
validates :image, presence: true
end
And my lists_controller.rb
:
class ListsController < ApplicationController
def list_params
params.require(:list).permit(:title, :image_attributes)
end
def create
@list = List.new(list_params)
if @list.save
redirect_to @list
else
render :action => "new"
end
end
end
And I have nested form in my new.html.erb
for lists. Everything works well if I don't use dynamic styles in Image
model. If I do so, the imageable_type
remains nil
when the image styles are processed. It is believed that the Paperclip processor comes in too early when everything related to the imageable aren't assigned. So the result is that I always have an image with 200x100
size even when the imageable is a List
.
I've been seeking around for a solution. But many solutions are for Rails 3 and failed in my app (like attr_accessible
solution and any solution intending to retrieve anything about the imageable). Now I'd be grateful if anyone can provide a clean solution before I give in and use STI or monkey-patch Active Record.