从upload.html.erb
我将一个包含数据的表单(包括图像和裁剪信息(x和y坐标,宽度和高度))提交给名为update_image
的控制器方法。然后,我想将此信息传递给模型(picture.rb
)并保存此图像的裁剪版本。
我正在使用Rails 5和Paperclip来存储图像。我遇到了以下两个我似乎无法解决的问题:
非常感谢帮助!
upload.html.erb
<form action="/update_image" enctype="multipart/form-data" accept-charset="UTF-8" method="post">
<input type="file" name="image" />
<input type="hidden" name="crop_x" value="0" />
<input type="hidden" name="crop_y" value="5" />
<input type="hidden" name="crop_width" value="200" />
<input type="hidden" name="crop_height" value="100" />
</form>
upload_controller.rb
def update_image
picture = Picture.new(image: params[:image])
end
picture.rb
class Picture < ActiveRecord::Base
has_attached_file :image, styles: {
cropped: "-crop #{@crop_w}x#{@crop_h}+#{@crop_x}+#{@crop_y}",
thumb: "100x100>"
}
end
答案 0 :(得分:1)
您正在寻找动态风格。
class Picture < ActiveRecord::Base
attr_accessor :crop_needed
has_attached_file :image, styles: Proc.new { |clip| clip.instance.attachment_sizes }
def attachment_sizes
crop_needed ? {
cropped: "-crop #{@crop_w}x#{@crop_h}+#{@crop_x}+#{@crop_y}",
thumb: "100x100>"
} : {thumb: "100x100>"}
end
end
从需要裁剪的控制器:
def update_image
picture = Picture.new
picture.crop_needed = true if params[:crop_x].present?
picture.image = params[:image]
picture.save
end
在您不需要裁剪的其他控制器中,只需将crop_needed
设置为false。