LoginSignup
32
29

More than 5 years have passed since last update.

rails console で行える処理をコマンドラインから実行する。

Last updated at Posted at 2014-03-12

Rails での DB に対して、内容チェックや内容変更の操作を shell スクリプトにしようと思った。

ネットで次の情報をみつけた。
- http://stackoverflow.com/questions/10313181/pass-ruby-script-file-to-rails-console

Pass ruby script file to rails console

  1. rails console -s で、手作業で行いたい操作を実行して動作を確認する。
  2. 上で入力したスクリプトを foo.rb に記載する。
  3. コマンドラインから $ bundle exec rails runner "eval(File.read 'foo.rb')" として実行することで、 foo.rb の内容を実行して、動作を確認する。
  4. コマンドラインで実行できるようになれば、   それを shell スクリプトから実行したり、 ruby から system() や open3() で実行することができる。

例:

  • devise でユーザー管理をしている rails アプリで、 特定のユーザーを削除する処理をコマンドライン化する。
  1. $ rails console -s で
    u = User.where('username=?', 'katoy')
    => ...
    u[0].delete
    => ...
    u = User.where('usernme=?', 'katoy')
    => [] 

   として、動作を確認する。

  1. foo.rb に処理を記載する。
    u = User.where('username=?', 'katoy')
    u.each {|user| user.delete }
    puts User.where('username=?', 'katoy').size
  1. コマンドラインで実行する。
    $ bundle exec rails runner "eval(File.read 'foo.rb')"
32
29
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
29