【发布时间】:2011-04-02 23:32:43
【问题描述】:
我的更新表单中有附件图片的预览。当用户在附件字段上收到验证错误时,就会出现问题。在这种情况下,图片缩略图 url 就好像上传的图片没有任何错误(它显示了未保存在服务器上的文件名)。
这是我在视图中获取图片网址的方式:
<%= image_tag(@product.photo.url(:medium)) %>.
控制器:
def update
@product = Product.find(params[:id])
@product.update_attributes(params[:product]) ? redirect_to('/admin') : render(:new)
end
def edit
@product = Product.find(params[:id])
render :new
end
型号:
class Product < ActiveRecord::Base
<...>
@@image_sizes = {:big => '500x500>', :medium => '200x200>', :thumb=> '100x100>'}
has_attached_file :photo, :styles => @@image_sizes, :whiny => false
validates_attachment_presence :photo
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'], :message => I18n.t(:invalid_image_type)
validates_attachment_size :photo, :less_than => 1.megabytes, :message => I18n.t(:invalid_image_size, :max => '1 Mb')
after_post_process :save_image_dimensions
<...>
end
UPD:最简单的解决方案是在控制器的更新操作中添加@photo_file_url = @product.photo.url(:medium),在视图中@product.update_attributes和<% @photo_file_url ||= @product.photo.url(:medium) %>之前。
【问题讨论】:
-
请为您的
edit和update操作提供您的代码。 -
它们非常简单。只有一些 CRUD 提示(
Product.find(params[:id])和@product.update_attributes(params[:product])分别用于编辑和更新)。 -
使用这些更新编辑现有帖子是一种更常见的做法。
标签: ruby-on-rails validation url paperclip