読者です 読者をやめる 読者になる 読者になる

僕のYak Shavingは終わらない

車輪の再発明をやめたらそこには壮大なYakの群れが

WEB+DBの詳解Rails3を流す その1 RailsインストールからScaffoldまで

WEB+DB PRESS Vol.58

WEB+DB PRESS Vol.58


諸々今のバージョンでやるんでちょっとだけ新しいこともやります。
できるだけ手順がわかるように書きました。

ちなみにコードは↓にあります。
kazuph/sample_rails_blog_app · GitHub

Ruby Gem,Gitのバージョン

» ruby --version
ruby 1.9.3p194 
» gem --version
1.8.23
» git --version
git version 1.7.3.4

Railsのinstall

» gem i rails
» rails --version
Rails 3.2.8

※rbenvの場合はgem i後にrbenv rehashが必要

bundleのinstall

あとで使うので

gem i bundle

プロジェクトの作成

» rails new blog_app
» cd blog_app
» tree -L 1
.
├── Gemfile
├── Gemfile.lock
├── README.rdoc
├── Rakefile
├── app
├── config
├── config.ru
├── db
├── doc
├── lib
├── log
├── public
├── script
├── test
├── tmp
└── vendor

11 directories, 5 files

git

git init 
git add .
git commit -m 'first new blog app'

scaffoldしちゃう

rails g scaffold post title:string body:text

gはgenerateのエイリアス

DBに反映

rake db:migrate

テスト実行

rake

サーバー起動

rails s

sはserverのエイリアス

f:id:kazuph1986:20121006141953j:plain

なにこれ超簡単

Sexy Validation(笑い)

なにこのネーミングw

» git diff app/models/post.rb
diff --git a/app/models/post.rb b/app/models/post.rb
index 93fd7c5..3a18c58 100644
--- a/app/models/post.rb
+++ b/app/models/post.rb
@@ -1,3 +1,6 @@
 class Post < ActiveRecord::Base
   attr_accessible :body, :title
+  validates :title,
+    :presence => true,
+    :length => {:maximum => 20}
 end

f:id:kazuph1986:20121006142935j:plain
ちゃんとエラー部分を強調表示してくれてる(^q^)
なにこれスゴすぎ。

pryでrails cできるようにする

なんかデフォだとirbらしいですが今はpryが流行りだと思うのでそっちで設定します。
参考:Railsでのpryコマンド利用設定&実行例 #Ruby #Rails #pry - Qiita
まずインストール

» gem install pry pry-doc pry-rails

続いてGemの編集

» git diff Gemfile
diff --git a/Gemfile b/Gemfile
index 5367a9a..bc12240 100644
--- a/Gemfile
+++ b/Gemfile
@@ -22,6 +22,12 @@ end

 gem 'jquery-rails'

+group :development do
+  gem 'pry'
+  gem 'pry-doc'
+  gem 'pry-rails'
+end
+
 # To use ActiveModel has_secure_password
 # gem 'bcrypt-ruby', '~> 3.0.0'

+とついている部分を適当な場所に追記して

» bundle install

で以下でコンソール起動。cはconsoleのc。

» rails c
/home/kazuph/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/irb/completion.rb:9:in `requi
re': cannot load such file -- readline (LoadError)
        from /home/kazuph/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/irb/completion.r
b:9:in `<top (required)>'
        from /home/kazuph/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railti
es-3.2.8/lib/rails/commands/console.rb:3:in `require'
        from /home/kazuph/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railti
es-3.2.8/lib/rails/commands/console.rb:3:in `<top (required)>'
        from /home/kazuph/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railti
es-3.2.8/lib/rails/commands.rb:38:in `require'
        from /home/kazuph/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/railti
es-3.2.8/lib/rails/commands.rb:38:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

はいエラー!
なにかなーと思ったら以下を発見
http://stackoverflow.com/questions/4922700/ruby-1-9-2-and-rails-3-cannot-open-rails-console

これするといいよとのことが書かれていた。

» gem install rb-readline

そして以下のように追記

» git diff Gemfile
diff --git a/Gemfile b/Gemfile
index bc12240..12f65ff 100644
--- a/Gemfile
+++ b/Gemfile
@@ -22,6 +22,8 @@ end

 gem 'jquery-rails'

+gem 'rb-readline'
+
 group :development do
   gem 'pry'
   gem 'pry-doc'

そして

» bundle install

で以下

» rails c
Loading development environment (Rails 3.2.8)
[1] pry(main)>

キタ――(゚∀゚)――!!

最終的なGemfile

» cat Gemfile
source 'https://rubygems.org'

gem 'rails', '3.2.8'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'


# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

gem 'rb-readline'

group :development do
  gem 'pry'
  gem 'pry-doc'
  gem 'pry-rails'
end

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
# gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'debugger'

ということで

rails cでvalidationの確認

pry(main)> Post.create!
   (0.0ms)  begin transaction
   (0.0ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Title can't be blank
from /home/homepage/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/validations.rb:56:in `save!'

「Title can't be blank」と出てます!なんかしらないけどすごい!

pry(main)> Post.create! :title => 'ぺ、ってなんだよ' * 3
   (0.0ms)  begin transaction
   (0.0ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Title is too long (maximum is 20 characters)
from /home/homepage/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/validations.rb:56:in `save!'

20文字以上も怒られますね。

Post.create! :title => 'ペ'
   (0.0ms)  begin transaction
Binary data inserted for `string` type on column `title`
  SQL (30.0ms)  INSERT INTO "posts" ("body", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?)  [["body", nil], ["created_at", Sat, 06 Oct 2012 06:12:18 UTC +00:00], ["title", "\xE3\x81\xBA"], ["updated_at", Sat, 06 Oct 2012 06:12:18 UTC +00:00]]
Encoding::UndefinedConversionError: "\xE3" from ASCII-8BIT to UTF-8: INSERT INTO "posts" ("body", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?)
   (0.0ms)  rollback transaction
ActiveRecord::StatementInvalid: Encoding::UndefinedConversionError: "\xE3" from ASCII-8BIT to UTF-8: INSERT INTO "posts" ("body", "created_at", "title", "updated_at") VALUES (?, ?, ?, ?)
from /home/homepage/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/activerecord-3.2.8/lib/active_record/connection_adapters/sqlite_adapter.rb:208:in `encode!'

発行されたINSERT文が見れます。ごいす~

とりあえずここまで。
次はコメント投稿機能を追加する。

WEB+DB PRESS Vol.58

WEB+DB PRESS Vol.58