如何在迁移中使用辅助方法?
How do I use helper methods in a Migration?
如何使用来自 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>
我鼓励你以不同的方式组织事情并创建一个服务 class 来处理这些事情,这真的不是迁移和助手的目的。例如,如果您在 class 中创建服务app/services
您可以轻松地从佣金测试中调用它。
你的帮手
module TestHelper
def test
puts 'TEST'
end
end
您的迁移,include
必须在迁移定义之外
include TestHelper
class Test < ActiveRecord::Migration[6.0]
def change
test
end
end
如何使用来自 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>
我鼓励你以不同的方式组织事情并创建一个服务 class 来处理这些事情,这真的不是迁移和助手的目的。例如,如果您在 class 中创建服务app/services
您可以轻松地从佣金测试中调用它。
你的帮手
module TestHelper
def test
puts 'TEST'
end
end
您的迁移,include
必须在迁移定义之外
include TestHelper
class Test < ActiveRecord::Migration[6.0]
def change
test
end
end