Ruby on rails ActiveRecord自定义字段方法

Ruby on rails ActiveRecord自定义字段方法,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,假设我有一个特定记录的自定义图像上传,我在模型中添加了两列 缩略图地址 缩略图路径 现在让我们假设我有一个带有:file字段的表单,它是以多部分形式上传的文件。我需要让模型在给定的散列中拾取文件,然后将其发送给一个自定义方法,该方法执行上载并将其保存为模型的一部分 现在我正在这样做: def initialize(options = nil) if options if options[:file] self.upload_thumbnail(options[:file]

假设我有一个特定记录的自定义图像上传,我在模型中添加了两列

缩略图地址 缩略图路径

现在让我们假设我有一个带有: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

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

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

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

您正在寻找的功能。只需定义:

def file
  # Read from file or whatever
end

def file=(value)
  # Upload thumbnail and store file
end
初始化
更新属性
,堂兄弟会为您选择方法

或者省去麻烦,按照Kandada的建议使用。

您正在寻找的。只需定义:

def file
  # Read from file or whatever
end

def file=(value)
  # Upload thumbnail and store file
end
初始化
更新属性
,堂兄弟会为您选择方法

或者像Kandada建议的那样省去麻烦和使用