PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 14, 2022

[FIXED] How do I use helper methods in a Migration?

 April 14, 2022     helper, migration, ruby-on-rails, ruby-on-rails-6     No comments   

Issue

How do I use a helper method like this from 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

Inside of a migration:

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

I know I can use a model's method but I don't want to copy and paste a bunch of the same methods in models just for migrations...otherwise I wouldn't have the helpers in the first place.

I get this error when trying to run my migration:

NoMethodError: undefined method `upload_s3' for #<CreateSeeds:0x00007fe4ee12bbc0>

Solution

I would encourage you to organize things differently and create a service class to handle these things, this is really not what migrations and helpers are for. If you create a service class in e.g. app/services you could call that from a rake test easily.

Your helper

module TestHelper
  def test
    puts 'TEST'
  end
end

your migration, the include has to be outside the migration definition

include TestHelper

class Test < ActiveRecord::Migration[6.0]
  def change
    test
  end
end


Answered By - Eyeslandic
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing