Ruby on Rails (プロジェクト作成編)
Project作成
$ rails new blog
JavaScript Runtime
$ vi Gemfile gem 'therubyracer', :platform => :ruby #を外す
DB作成
$ rake db:create
Post(Model/DB/Controller/URL/View)
・Model作成/DBに反映
$ Rails generate model Post title:string content:text $ Rails g model Post title:string content:text $ rake db:migrate
・Controller作成
$ rails g controller Posts
・URL設定
vi config/routes.rb 2行目に追記 resources :posts
URL確認
$ rake routes posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new(.:format) posts#new edit_post GET /posts/:id/edit(.:format) posts#edit post GET /posts/:id(.:format) posts#show PUT /posts/:id(.:format) posts#update DELETE /posts/:id(.:format) posts#destroy
番外編:デバッグ用コマンド
$ rails console $ rails dbconsole
readlineがないと怒られる。
# yum install readline-devel $ cd ~/.rvm/src/ruby-1.9.3-p194/ext/readline/ $ ruby extconf.rb $ make $ sudo make install
・Viewで使える記法
- コントローラー内で定義された@変数はそのまま使えます。
- <% %>のなかではrubyの命令を使える
- <%= %>は表示させるための命令(Escapeされる)
- <% # コメント %>
・Controllerにメソッド追加
- PostController
- index 一覧 -> app/views/posts/index.html.erb
- create
- new
- edit
- show
- update
- destroy