配合post,增加comment功能,從上手指南7開始。
要注意一下中文的指南還是舊的,照著做會出錯的,大約從英文版的指南 6.4 Generating a Controller
開始看,再對照修改一下,以下列出重點。
先來產生 Model
rails generate model Comment commenter:string body:text post:references
沒有用到scaffolding,只建了model
/////////////////////////////////////////////////////////////////////////
CommentsController.rb的內容改成如下:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id]) #是這篇留言所屬的文章
@comment = @post.comments.create(comment_params) #留言本身
redirect_to post_path(@post) #最後回到show action顯示 app/views/posts/show.html.erb
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
////////////////////////////////////////////////////////////
app/views/posts/show.html.erb 增加了留言的顯示與輸入
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<p>
<b>Commenter:</b>
<%= comment.commenter %>
</p>
<p>
<b>Comment:</b>
<%= comment.body %>
</p>
<% end %>
<%= form_for([@post, @post.comments.build]) do |f| %>
<div class="field">
<%= f.label :commenter %><br />
<%= f.text_field :commenter %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
然後文章跟留言都可以運作,接著依指南往下做就好了。
沒有留言:
張貼留言