我正在研究如何使用来自 Sixrevisions.com 的 Ruby on Rails 教程从头开始创建博客。
当我运行服务器并创建新帖子时,我没有可见的选项来添加评论。根据教程,我应该能够将结束编辑评论添加到创建的帖子中。
我的comments_controller.rb:
class CommentsController < ApplicationController
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @comments }
end
end
# GET /comments/1
# GET /comments/1.json
def show
@comment = Comment.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @comment }
end
end
# GET /comments/new
# GET /comments/new.json
def new
@comment = Comment.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @comment }
end
end
# GET /comments/1/edit
def edit
@comment = Comment.find(params[:id])
end
# POST /comments
# POST /comments.json
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(params[:comment])
redirect_to @post
end
# PUT /comments/1
# PUT /comments/1.json
def update
@comment = Comment.find(params[:id])
respond_to do |format|
if @comment.update_attributes(params[:comment])
format.html { redirect_to @comment, notice: 'Comment was successfully
updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url }
format.json { head :no_content }
end
end
end
显示.html.erb
<p>
<b>Title:</b>
<%=h @post.title %>
</p>
<p>
<b>Body:</b>
<%=h @post.body %>
</p>
<h2>Comments</h2>
<% @post.comments.each do |c| %>
<p>
<b><%=h c.name %> said:</b><br />
<%= time_ago_in_words(c.created_at) %> ago
</p>
<p>
<%=h c.body %>
</p>
<% end %>
<% form_for [@post, Comment.new] do |f| %>
<p>
<%= f.label :name, "Author" %><br />
<%= f.text_field :name %><br />
<%= f.label :body, "Comment Description" %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit "Add Comment" %>
</p>
<% end %>
耙路线
post_comments GET /posts/:post_id/comments(.:format) comments#index
POST /posts/:post_id/comments(.:format) comments#create
new_post_comment GET /posts/:post_id/comments/new(.:format) comments#new
edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit
post_comment GET /posts/:post_id/comments/:id(.:format) comments#show
PUT /posts/:post_id/comments/:id(.:format) comments#update
DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
/:controller/:action/:id(.:format) :controller#:action
/:controller/:action/:id.:format :controller#:action
root / posts#index
感谢您的帮助和兴趣!