[英]Paperclip conditional styles
我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
您正在尋找動態樣式。
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即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.