2011年5月21日土曜日

rails コメント投稿機能の追加


WEB+DB 58  25ページぐらいにあります。
少し複雑になっているけど、コメント追加部分だからこんなもんだと思う。

----------------------------------
ItemにCommentモデルを追加していくサンプル
----------------------------------
//コメントモデルを作成  
$rails g model comment item:references comment:string name:string
$rake db:migrate

//コメントのコントローラー作成
$rails g controller comments

//itemsとcommentsにhas_manyの関係を持たす
app/models/item.rb
has_many :comments


//itemsの中にcommentsのルーティグを追加
confit/routes.rb
resources :items do
  resources :comments, :only =?[:new, :create]
end

//パーシャル作成命令(これはいい感じ。)
app/views/items/show.html.erb
の下の方
<%= render @item.comments.build %>


//パーシャルの実体
app/views/comments/_comment.html.erb
<%= form_for [comment.item, comment] do |f| %>


    <%= f.label :comment , 'any comment?' %>
    <%= f.text_field :comment %>
 

 

    <%= f.label :name ,'who are you?' %>
    <%= f.text_area :name %>
 

 

    <%= f.submit %>
 

<% end %>

//itemに関連したcomment作成
app/controllers/comments_controller.rb
の下の方
class CommentsController < ApplicationController
def create
item = Item.find params[:item_id]
item.comments.create params[:comment]
redirect_to item
end
end

// コメントの表示
app/views/items/show.html.erb
の下の方
comment
<% @item.comments.each do |comment| %>
<%= "#{comment.comment} by #{comment.name}" %>
<% end %>


0 件のコメント:

コメントを投稿