How do I run a Ruby file in a Rails environment?

前端 未结 4 1344
名媛妹妹
名媛妹妹 2020-12-12 18:22

I want to run a Ruby file in the context of a Rails environment. rails runner almost does what I want to do, but I\'d like to just give it the file name and arguments. I\'m

4条回答
  •  -上瘾入骨i
    2020-12-12 19:22

    This is an old question, but in my opinion I often find it helpful to create a rake task... and it's actually very easy.

    In lib/tasks/example.rake:

    namespace :example do
    
    desc "Sample description you'd see if you ran: 'rake --tasks' in the terminal"
    task create_user: :environment do
      User.create! first_name: "Foo", last_name: "Bar"
    end
    

    And then in the terminal run:

    rake example:create_user
    

    Locally this will be run in the context of your development database, and if run on Heroku it will be run while connected to your production database. I find this especially useful to assist with migrations, or modified tables.

提交回复
热议问题