我如何使用application_helper.rb
中的此类帮助方法:
def upload_s3(region, file, bucket, filepath)
s3 = Aws::S3::Resource.new(region: region)
obj = s3.bucket(bucket).object(filepath)
obj.upload_file(file)
end
迁移中:
class CreateSeeds < ActiveRecord::Migration[6.0]
pdf = "https://#{bucket}.s3.#{region}.amazonaws.com/#{record["filepath"]}"
name = tokenize_by_delimiter_case(".", record["filepath"], 0)
path = "items/#{name}"
upload_s3(region, pdf, bucket, path)
end
[我知道我可以使用模型的方法,但是我不想为迁移而在模型中复制和粘贴一堆相同的方法...否则,我一开始就没有助手。
尝试运行迁移时出现此错误:
NoMethodError: undefined method `upload_s3' for #<CreateSeeds:0x00007fe4ee12bbc0>
我鼓励您以不同的方式组织事情,并创建一个服务类来处理这些事情,这实际上不是迁移和帮助程序的目的。如果您在(例如)中建立服务类别app/services
您可以从抽水测试中轻松调用它。
您的助手
module TestHelper
def test
puts 'TEST'
end
end
您的迁移,include
必须在迁移定义之外
include TestHelper
class Test < ActiveRecord::Migration[6.0]
def change
test
end
end