僕のYak Shavingは終わらない

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

WEB+DB 詳解Ruby on Rails を流す その2 コメント機能追加

WEB+DB PRESS Vol.58

WEB+DB PRESS Vol.58


WEB+DBの詳解Rails3を流す その1 - 僕の車輪の再発明
前回の続き。

2年前の記事ですが、現行バージョンのRubyRailsでやってみてます。

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

コメント機能の実装

まずモデル

» rails g model comment post:references comment:string name:string
» rake db:migrate

次にコントローラー

» rails g controller comments

投稿とコメントのモデルの関連設定

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

コメント機能のルーティング

» git diff config/routes.rb 
diff --git a/config/routes.rb b/config/routes.rb
index 3a5e358..49b2dbb 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,5 +1,7 @@
 BlogApp::Application.routes.draw do
-  resources :posts
+  resources :posts do
+    resources :comments, :only => [:new, :create]
+  end

コメントのViewの追加

» git diff app/views/posts/show.html.erb 
diff --git a/app/views/posts/show.html.erb b/app/views/posts/show.html.erb
index c1bea45..0a54aa5 100644
--- a/app/views/posts/show.html.erb
+++ b/app/views/posts/show.html.erb
@@ -10,6 +10,8 @@
   <%= @post.body %>
 </p>
 
+<hr>
+<%= render @post.comments.build%>
 
 <%= link_to 'Edit', edit_post_path(@post) %> |
 <%= link_to 'Back', posts_path %>

コメント投稿フォームをつくる

app/views/comments/_comment.html.erb
<%= form_for [comment.post, comment] do |f| %>
  <div class="field">
    <%= f.label :comment, 'any comment?'%><br />
    <%= f.text_area :comment%>
  </div>
  <div class="field">
    <%= f.label :name, 'who are you?'%><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.submit %>
  </div>
<% end %>

コントローラーの記述

comments_controller.rb
class CommentsController < ApplicationController
  def create
    post = Post.find params[:post_id]
    post.comments.create params[:comment]
    redirect_to post
  end
end

コメント表示を追加

show.html.erb
<p>
  <b>comments:</b>
  <%= @post.comments.each do |comment| %>
    <p>
    <%= "#{comment.comment} by #{comment.name}"%>
    </p>
  <% end %>
</p>

本を写してたのでかなりtypoしてしまいましたorz
でもその御蔭でちょっと詳しく見ることができたので良かったです。
これがベーマガ方式・・・。

f:id:kazuph1986:20121006205101j:plain
なんかJSがデバッグモードになっている気がする?

まあ今回はとりあえずこんな感じで。