2016-12-01 76 views
0

upload.html.erb我正在向数据提交表单,其中包括图像和裁切信息(x和y坐标,宽度和高度) - 到称为update_image的控制器方法。然后我想将这些信息传递给模型(picture.rb)并保存此图像的裁剪版本。回形针条件样式

我正在使用Rails 5和Paperclip来存储图像。我遇到了以下两个我似乎无法解决的问题:

  1. 如何访问我的模型中的作物信息数据?我不想将作物信息保存在数据库中。
  2. 如何裁剪图像只有如果作物信息存在? (我想用从另一种形式的常规文件上传同一型号不具有作物功能)

帮助是非常感谢!

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 

回答

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。