RailsコーディングHack

Ryoは記憶力があまりないので、いっつも各modelがどんなアトリビュートとリレーションを持っているか忘れてしまう。そんな時今までは、わざわざmigrationのファイルを見たりとか、mysqlコマンドを叩いて調べていた。


しかーし、それでは効率がとても悪いので、 各modelの構造を出力・印刷してチートシートにしてみた。


create_table_cheat_sheet.rb


#production環境とかのものを出力したければ、適宜変更のこと。
ENV['RAILS_ENV'] ||= 'development'

require './config/boot'
require './config/environment'


models = Array.new

Dir.glob("./app/models/*rb") { |f|
f.match(/\/([a-z_]+).rb/)
c_name = $1.camelize
puts c_name
klass = eval(c_name)
if klass.superclass == ActiveRecord::Base
models << klass
end
}

fout = open('./table_cheat.txt','w')

models.each{ |each_model|
fout.puts '---' + each_model.to_s
#テーブルのカラムを列挙
tmp_obj = each_model.new
tmp_obj.attributes.each{ |attribute|
fout.puts attribute[0]
}

fout.puts''
#リレーションを列挙
each_model.reflect_on_all_associations.each { |relation|
fout.puts relation.name.to_s + '[' + relation.name.to_s.camelize.singularize + ']' + ' : ' + relation.macro.to_s
}

fout.puts ''
}

fout.close


これをRailsプロジェクトのルートで

ruby create_table_cheat_sheet.rb


とすると、実行したディレクトリにtable_cheat.txtというテキストファイルができる↓


#Kikkerの例


---Counter
rss_count
html_count
target_date
api_count


---TasteEntry
user_id

user[User] : belongs_to
user_keywords[UserKeyword] : has_many

---User
name
mail_address
nickname
regist_at
password
age

user_preference[UserPreference] : has_one
taste_entries[TasteEntry] : has_many

---UserKeyword
tfidf_value
taste_entry_id
keyword

taste_entry[TasteEntry] : belongs_to

---UserPreference
point_threthold
hatebu_name
user_id
is_use_hatebu_learn
arrange_entry_count
simirality_threthold

user[User] : belongs_to


これを印刷して、デスクにでも貼っておけば、コーディングの効率向上間違いなし!!
#補完が効く開発環境があればこんな事しなくてもいいんだけどねぇ



さらに可視化したい方はコチラ↓


[Model同士の関係をグラフで表示するプラグイン]
http://rails.office.drecom.jp/takiuchi/daily/200608/09
[hackdiary: Using Omnigraffle to visualise Rails model associations]
http://www.hackdiary.com/archives/000093.html





キーワード: ruby on rails Rails DB データベース 構造 出力 リレーション relation model モデル ActiveRecord