ActiveRecord自定义字段方法

时间:2010-07-07 19:47:59

标签: ruby-on-rails ruby activerecord

让我们想象一下,我为特定记录上传了一个自定义图像,并在模型中添加了两列。

thumbnail_url thumbnail_path

现在假设我有一个带有:file字段的表单,它是多部分表单中的上传文件。我需要以某种方式让模型拾取给定哈希中的文件,然后将其发送到执行上载的自定义方法,并将其保存为模型的一部分。

现在我正在这样做:

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

它有效,但我在这里做了一些不必要的重写。有更简单的方法吗?什么东西只需要覆盖一个方法?

2 个答案:

答案 0 :(得分:2)

您正在寻找virtual attributes。只需定义:

def file
  # Read from file or whatever
end

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

initializeupdate_attributes和堂兄会为您挑选方法。

那或者保存麻烦并使用paperclip作为Kandada的建议。

答案 1 :(得分:0)

您是否考虑过使用paperclip gem?它执行您在问题中描述的功能。