【发布时间】:2015-12-18 18:37:13
【问题描述】:
基本上我有一个Image 模型,它多态属于imageable,到目前为止是List 和Item。由于图像将具有自己的属性和关系,我不想将图像视为List 和Item 的属性并将其搞砸。所以我创建了Image 模型。
我想要实现的是List 应该有一个徽标拇指图像,其中高度等于宽度,但Item 具有不同的样式。 Paperclip 文档告诉我们使用lambda 创建动态样式。所以这是我的Image 模型:
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
还有我的List 模特:
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
还有我的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
我在new.html.erb 中有嵌套表单用于列表。 如果我在Image 模型中不使用动态样式,一切都会很好。如果我这样做,imageable_type 在处理图像样式时仍然是nil。人们认为,当与 imageable 相关的所有内容都没有分配时,Paperclip 处理器就来得太早了。所以结果是我总是有一个大小为200x100 的图像,即使图像是List。
我一直在寻找解决方案。但是许多解决方案适用于 Rails 3,但在我的应用程序中失败了(例如 attr_accessible 解决方案和任何打算检索有关可成像的任何内容的解决方案)。现在,如果有人能在我放弃并使用 STI 或猴子补丁 Active Record 之前提供一个干净的解决方案,我将不胜感激。
【问题讨论】:
标签: ruby-on-rails ruby paperclip