假设我为特定记录上传了自定义图像,并在模型中添加了两列。
thumbnail_url 缩略图路径
现在让我们想象一下,我有一个带有 :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
它有效,但我在这里做了一些不必要的重写。有更简单的方法吗?只需要覆盖一种方法的东西?
最佳答案
您正在寻找virtual attributes .只需定义:
def file
# Read from file or whatever
end
def file=(value)
# Upload thumbnail and store file
end
和initialize
、update_attributes
和 cousins 将为您选择方法。
那个,或者省去麻烦并使用 paperclip正如 Kandada 建议的那样。
关于ruby-on-rails - ActiveRecord 自定义字段方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3198284/