LoginSignup
5
5

More than 5 years have passed since last update.

[Rails]modelファイルを全部まとめてdestroy

Posted at

やりたいこと(困っていること)

(あんまり無いけど)途中まで作ったRailsアプリのModelを全部削除して、最初から作り直したいことがあった。
そのときのモデル数は15個くらいあって、モデル名をひとつひとつ入力しては削除するのがめんどくさかった。rails destroyコマンドの引数に渡せるモデル名が1つだけだったのもツライ。

やったこと

Dir.globでファイル一覧を取得して、それぞれにrails destroyコマンドを投げた。うまくいった。ハッピー!

[~/path/to/rails/app]
% ruby -e 'Dir.glob("app/models/*.rb").each{|f| puts %x|rails destroy model #{File.basename(f, ".rb")}| }'
      invoke  mongoid
      remove    app/models/model01.rb
      invoke  mongoid
      remove    app/models/model02.rb

私がORMにmongoidを利用しているのでinvokeのところがmongoid表記になっているが、ActiveRecordでも動作は変わらないはず。

ちなみに、実際にファイルを削除せず、動きを確認するだけにとどめたい場合はrailsコマンド部分の最後に--pretendを付けると良い(ドライラン)。

環境情報

OS, Kernel

os,kernel
% inxi -SM
System:    Host: hostname Kernel: 2.6.32-504.el6.x86_64 x86_64 (64 bit) Console: tty 1
           Distro: CentOS release 6.6 (Final)
Machine:   System: VMware product: VMware Virtual Platform
           Mobo: Intel model: 440BX Desktop Reference Platform
           Bios: Phoenix v: 6.00 date: 04/14/2014

Ruby, Rails

ruby
% ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
rails
% rake about
About your application's environment
Rails version        4.2.1
Ruby version         2.1.2-p95 (x86_64-linux)
RubyGems version     2.2.2
Rack version         1.5
5
5
0

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
5
5