Search code examples
ruby-on-railsrails-console

Executing a ruby script from the Rails console


Rails 3.2

I have a running rails application, with a Company MVC.

in the models/company.rb, I have the following method:

def save_company_pay_num
  return false unless self.valid?
  create_company_pay_num if self.company_pay_num.blank?
  res = save_check_company_pay_num
  unless res[0]
    errors.add(:set_company_pay_num, res[1].try{|r| r.split(':')[1].strip.capitalize})
    return false
  end
  true
end 

I have about 1,000 companies, that need to have their pay numbers re-issued.

Is there a way, from the rails console (rails c), to execute a file, something like:

reset_pay_num.rb

company_ids=[
  '1',
  '2',
  '3',
  ...
]

company_ids.each do |c|
  company = Company.find(c)
  company.save_company_pay_num
end

Solution

  • I don't know what's the reason for such behavior because at least you can put your script as a method inside some file required by rails but:

    eval(File.read 'reset_pay_num.rb')
    

    will do the trick.