Paperclip polymorphic styles

戏子无情 提交于 2020-01-05 12:14:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!