问题
I have a polymorphic model where my attachment's styles are defined with Paperclip's lambda. Here is the problem: polymorphic properties such as attachable_id
and attachable_type
are both nil
. There is no controller because I'm using ActiveAdmin.
My Project model:
class Project < ActiveRecord::Base
has_many :attachments, as: :attachable, :dependent => :destroy
accepts_nested_attributes_for :attachments, allow_destroy: true
attr_accessible :floors, :intro, :name, :price, :square, :deadline, :is_visible, :attachments_attributes
validates_presence_of :floors, :intro, :name, :price, :square, :deadline
validates_numericality_of :floors, :price, :square
validates_length_of :name, :deadline, maximum: 60
def set_styles
{ thumb: '150x90#', big: '1366x768#' }
end
end
My Attachment model:
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
attr_accessible :about, :position, :is_main_image, :is_blueprint, :attachment, :attachment_file_name, :attachable_attributes
accepts_nested_attributes_for :attachable
has_attached_file :attachment, styles: lambda { |a| a.instance.attachable.set_styles }
validates_attachment_presence :attachment
validates_attachment_size :attachment, :less_than => 3.megabytes
end
And my view:
<%= semantic_form_for [:admin, @project], html: { multipart: true } do |f| %>
<%= f.inputs do %>
<%= f.input :is_visible, as: :boolean %>
<% end %>
<%= f.inputs do %>
<%= f.input :name %>
<%= f.input :intro %>
<% end %>
<%= f.inputs do %>
<%= f.input :square %>
<%= f.input :floors %>
<%= f.input :price %>
<%= f.input :deadline %>
<% end %>
<%= f.inputs do %>
<%= f.input :attachments, as: :file, input_html: { multiple: true, name: 'project[attachments_attributes][][attachment]' } %>
<% @project.attachments.each do |a| %>
<div class="image-container-<%= a.id %>">
<%= link_to image_tag(a.attachment.url :thumb), edit_admin_attachment_path(a.id), class: (a.is_main_image ? 'main_image' : 'not_main_image') %>
<%= link_to 'Delete image', delete_attachment_admin_attachment_path(a.id), class: 'button', remote: true, method: :delete %>
</div>
<% end %>
<% end %>
<%= f.actions %>
<% end %>
来源:https://stackoverflow.com/questions/19901485/paperclip-polymorphic-styles