Reputation: 286
From upload.html.erb
I am submitting a form with data - including an image and crop information (x and y coordinates, width and height) - to a controller method called update_image
. I then want to pass this information on over to the model (picture.rb
) and save a cropped version of this image.
I'm using Rails 5 and Paperclip to store images. I've ran into the following two problems which I don't seem to be able to solve:
Help is greatly appreciated!
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
Upvotes: 0
Views: 221
Reputation: 22956
You are looking for dynamic styles.
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
From the controller where you need cropping:
def update_image
picture = Picture.new
picture.crop_needed = true if params[:crop_x].present?
picture.image = params[:image]
picture.save
end
From the other controller where you do not need cropping, just set crop_needed
to false.
Upvotes: 1