White scenery @showyou, hatena

If you have any comments, you may also send twitter @shsub or @showyou.

Getting Started with Rails

http://guides.rubyonrails.org/getting_started.html見ながら実際に動かしてみる。

3.2 Creating the Blog Application

$ rails blog -d mysql

blogデイレクトリが作成されて、いろいろファイルができた。test用環境ができてるのは大きいなぁ。djangoとかpylonsにはあったっけ?

3.3.2 Configuring a MySQL Database

config/database.ymlのusername,passwordを自分の環境に書き換えた

3.4 Creating the Database

$ rake db:create

を実行してDBを作った。

4 Hello, Rails!

$ script/generate controller home index
exists app/controllers/
exists app/helpers/
create app/views/home
exists test/functional/
create app/controllers/home_controller.rb
create test/functional/home_controller_test.rb
create app/helpers/home_helper.rb
create app/views/home/index.html.erb

って出てきた。これcontrolleとhomeとindexを作ってるの?後で調べる必要があるな

4.1 Starting up the Web Server

$ script/server

でサーバを起動させる。WEBrickってRubyの組み込みhttpdだっけ?

別マシンからhttp://ip:3000につなぐ。が、localじゃ無いのでこのままだとつなげられない。

$ script/server -b ip

と指定すればつながる。

4.2 Setting the Application Home Page

自分なりに解釈して、config/routes.rbにroutingの設定があるからそれの最後の一個前の行に

map.root :controller => "home"

って入れた。サーバをリロードするとルートがapp/views/home/index.html.erbになった。

6 Creating a Resource

script/generate scaffold Post name:string title:string content:text

このPostってのは決まった名前?それともHogeとかやったらhoge.rbとかhogesとか付くのだろうか。。前者に見えるけど。

6.1

$ vim db/migrate/001_create_posts.rb

class CreatePosts < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.string :name
      t.string :title
      t.text :content

      t.timestamps
    end
  end

  def self.down
    drop_table :posts
  end
end

up,downってメソッド? drop_table :postsとかの書式がわからん。。

rake db:migrate

でテーブルを作る。

6.2 Adding a Link

$ vim app/views/home/index.html.erb

とファイルを開き、

Hello, Rails!

<%= link_to "My Blog", posts_path %>

と書き換えた

6.3 Working with Posts in the Browser

ブラウザを立ち上げてpostのページが作れたことを確認。

6.5 Adding Some Validation

モデルへの入力チェックをつける。app/model/post.rb

class Post < ActiveRecord::Base
validates_presence_of :name, :title
validates_length_of :title, :minimum => 5
end

未だにrubyの文法が良くわからないので確認すると、

hogeruby内部で定義してるシンボルにアクセスできる。上の例だと
nameとか:titleっていうのを数値に結びつけるんでしょうか。

validates_presence_ofはhttp://d.hatena.ne.jp/zariganitosh/20061110/1163164738見た感じ「ちゃんと値が入ってるかどうか確認する」ってルールなのか。その次のは「長さの比較で」でタイトルが5以上。

6.6 Using the Console

$ script/console

でconsoleを立ち上げて(中身はirb?)、6.5のValidationの挙動を確認する

p = Post.create(:content => "A new post")
p.save

Postオブジェクトを作成して、保存する。p.saveでエラーが出て、

p.errors
=> #, @errors={"name"=>["can't be blank"], "title"=>["can't be blank", "is too short (minimum is 5 characters)"]}>

と、"name"や"title"が空じゃ駄目で、"title"が5文字以上必要ということが出てくる。

6.7 Listing All Posts

app/controllers/posts_controller.rb見るとdefなんちゃらってクラスメソッドが並んでる。これどうやって振り分けるんだって思ったが、どうもconfig/routes.rbでマッチさせて振り分けてるっぽい。


map.connect ':controller/:action/:id'ならhoge/foo/barってurlを与えたときにHogeコントローラのfooってとこに:id=barとして割り振られる・・のか?他にもpost/deleteとかで違う挙動してそうだが。

参考


あと

format.html # index.html.erb  
format.xml { render :xml => @posts } 

が文法的に謎。format.htmlはもしかしてhtmlっていうメソッドか?てっきり設定ファイルのデータだと思ってた。それを踏まえたうえでformat.xmlになんで{}がついてるのかもわからんし。

6.8 Customizing the Layout

scaffoldによってページが作成されてるので自分でapp/views/layouts/posts.html.erbとか編集するとデザインを変えられるって話

6.9 Creating New Posts

respond_toってなんだっけ?->http://wota.jp/ac/?date=20060317

The new.html.erbではform_forだかfだかでformを記述している。

<h1>New post</h1>

<%= error_messages_for :post %>

<% form_for(@post) do |f| %>
  <p>
    <b>Name</b><br />
    <%= f.text_field :name %>
  </p>

  <p>
    <b>Title</b><br />
    <%= f.text_field :title %>
  </p>

  <p>
    <b>Content</b><br />
    <%= f.text_area :content %>
  </p>

  <p>
    <%= f.submit "Create" %>
  </p>
<% end %>
<%= link_to 'Back', posts_path %>

と書くと

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>Posts: new</title>
  <link href="/stylesheets/scaffold.css?1238675660" media="screen" rel="stylesheet" type="text/css" />
</head>
<body style="background: #EEEEEE;">

<p style="color: green"></p>

<h1>New post</h1>

<form action="/posts" class="new_post" id="new_post" method="post"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="ほげ" /></div>
  <p>
    <b>Name</b><br />
    <input id="post_name" name="post[name]" size="30" type="text" />
  </p>

  <p>
    <b>Title</b><br />

    <input id="post_title" name="post[title]" size="30" type="text" />
  </p>

  <p>
    <b>Content</b><br />
    <textarea cols="40" id="post_content" name="post[content]" rows="20"></textarea>
  </p>

  <p>
    <input id="post_submit" name="commit" type="submit" value="Create" />
  </p>
</form>
<a href="/posts">Back</a>
</body>
</html>

と出力される。

formのCreateボタン(submitボタン)が押されるとコントローラのcreateメソッドが呼ばれる。・・createとかupdateは予約語?

発言の投稿に成功したらflash[:notice]にあるメッセージも一緒に表示される。失敗ならばエラーメッセージが表示される。

・・いまさら思ったけど、.xmlとか指定するとそのままapiとして使えるのか?

6.10 Showing an Individual Post

/posts/1.htmlとか呼ぶと、id=1としてid番目の投稿を表示する。ここもshowとか定義されてるのかなぁ。

6.11 Editing Posts

/posts/1/editとか呼ぶと、コントローラのeditメソッドとedit.htmlが呼ばれる。
Updateボタンが押されるとコントローラのupdateメソッドが呼ばれる。もしかしてCreate->create,Update->updateって先頭を小文字にしてるのか?

6.12 Destroying a Post

deleteのリンクを踏むと発言が消される。出力されてるhtmlのソース見る限りだと、

var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete');

って感じに_method変数にdeleteを入れてる。

7 DRYing up the Code

7.1 Using Partials to Eliminate View Duplication

部分テンプレートを使って重複を減らす。
どうも<%= render :partial => "hoge" %> とか書いて、_hoge.html.erbを呼ぶとよさげですね。
http://maskana.homedns.org/rails/pro/body/15

7.2 Using Filters to Eliminate Controller Duplication

before_filterを使ってコントローラの各メソッド共通の処理をまとめる。
http://wota.jp/ac/?date=20050720#p01