2016-12-01 74 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。