Search code examples
ruby-on-railspapercliprmagick

Rails: Passing variable from form to model


I have a form, where users can upload a picture and can choose a watermark from a list. The value in the field is then the URL of the watermark (for simplification in development). I need to pass the chosen watermark_url to the model, so that rmagick can add the watermark. I use paperclip for the uploads.

In my model I have the following:

class Image < ActiveRecord::Base
...

attr_accessor :watermark_url

has_attached_file :picture, :processors => [:watermark], styles: {
thumb: '100x100>',
medium:{
    geometry: '300x300>',
    watermark_path:  Rails.root.join(watermark_url),
    position: "Center"}
}
end

watermark_url is a field in the form and in the database (which would not be necessary). Then I get the following error: undefined local variable or method `watermark_url'.

Am i missing something here?

Thank you in advance for helping!


Solution

  • With your helpful comments I found a solution using lambda to access the instance and its variables. I asked the user for the path of the watermark first, save it and then he uploads his picture.

    has_attached_file :picture, :processors => [:watermark], :styles => lambda { |a|
    {thumb: '100x100>',
    medium:{
        geometry: '300x300>',
        watermark_path:  Rails.root.to_s + "/public#{a.instance.watermark_url}",
        position: "Center"}
    }}