开发者

ActiveRecord Custom Field Method

开发者 https://www.devze.com 2023-01-06 13:28 出处:网络
Lets imagine that I have a custom image upload for a particular record and I add two columns into the model.

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(o开发者_如何学运维ptions[: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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消