Using the Console, Listing All Posts
Consoleをから操作できる。デバックのとき素早くなれるかも。
$ rails consoleLoading development environment (Rails 3.2.8) irb(main):001:0> p = Post.new(:content => "A new post") => #<Post id: nil, name: nil, title: nil, content: "A new post", created_at: nil, updated_at: nil> irb(main):002:0> p.save (0.1ms) begin transaction (0.1ms) rollback transaction => false irb(main):003:0> p.errors.full_messages => ["Name can't be blank", "Title can't be blank", "Title is too short (minimum is 5 characters)"] irb(main):004:0> p.errors => #<ActiveModel::Errors:0x007fd624f480b0 @base=#<Post id: nil, name: nil, title: nil, content: "A new post", created_at: nil, updated_at: nil>, @messages={:name=>["can't be blank"], :title=>["can't be blank", "is too short (minimum is 5 characters)"]}>
コーソルの起動中にコードを更新しても、反映されないので注意。警告が出る。
これまでは
http://localhost:3000/posts
にアクセスして投稿の一覧ページが表示されていたけど
http://localhost:3000/posts.json
後ろに.jsonをつけるとjsonで返してくれる。
この辺の記述のおかげ。
vim app/controllers/posts_controller.rb
1 class PostsController < ApplicationController 2 # GET /posts 3 # GET /posts.json 4 def index 5 @posts = Post.all 6 7 respond_to do |format| 8 format.html # index.html.erb 9 format.json { render json: @posts } 10 end 11 end
すごい至れり尽くせり感。
自分でフレームワーク作るときは思想に沿いつつ、こういうの見習えばいいのかな。