matsko
matsko

Reputation: 22183

ActiveRecord Custom Field Method

Lets imagine that I have a custom image upload for a particular record and I add two columns into the model.

thumbnail_url thumbnail_path

Now lets imagine that I have a form with a :file field which is the uploaded file in multipart form. I would need to somehow have the model pickup the file within the given hash and then issue it over to a custom method which performs the upload and saves it as apart of the model.

Right now I'm doing this:

def initialize(options = nil)
  if options
    if options[:file]
      self.upload_thumbnail(options[:file])
      options.delete(:file)
    end
    super options
  else
    super
  end
end

def update_attributes(options = nil)
  if options
    if options[:file]
      self.upload_thumbnail(options[:file])
      options.delete(:file)
    end
    super options
  else
    super
  end
end

It works, but I am doing some unnecessary overriding here. Is there a simpler way of doing this? Something that would only require overriding perhaps one method?

Upvotes: 1

Views: 1148

Answers (2)

Chubas
Chubas

Reputation: 18043

You are looking for virtual attributes. Just define:

def file
  # Read from file or whatever
end

def file=(value)
  # Upload thumbnail and store file
end

and initialize, update_attributes and cousins will pick the methods for you.

That, or save the hassle and use paperclip as Kandada suggested.

Upvotes: 3

Harish Shetty
Harish Shetty

Reputation: 64363

Have you considered using using paperclip gem? It performs the functions you describe in your question.

Upvotes: 1

Related Questions