我正在按照rails 3指南学习rails。
博客应用程序现已运行,但是我想让评论可编辑,并在帖子显示页面中进行更新,创建表单。所以我做了以下修改:
post.show.htm.erb:
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<tr>
<td><%= comment.commenter %></td>
<td><%= comment.body %></td>
<td><%= link_to 'Edit', edit_post_comment_path(@post,comment) %></td>
<td><%= link_to 'Destroy', post_comment_path(@post,comment), confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
<h2>Add a comment:</h2>
#here,I can not set the form_for property.
<%= form_for([@post,@comment],:url=>post_comment_path) 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 %>
控制器控制器:
class CommentsController < ApplicationController
# GET /posts/1/comments/1/edit
def edit
#render json: params
@post=Post.find(params[:post_id])
@comments=Comment.all
@comment = Comment.find(params[:id])
render "/posts/show"
end
#other action omitted
def show
# I donot know what to do here
end
end
但是我无法访问该链接:
http://localhost:3000/posts/1
我收到错误:
No route matches {:action=>"show", :controller=>"comments"}
事实上,你可以看到我在CommentController中有show动作。
并且,我想知道它为什么会访问评论#show action?
这是我的路线:
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
home_index GET /home/index(.:format) home#index
root / home#index
/posts/:id
会触发posts#show
。为什么comments#show
?
答案 0 :(得分:0)
如果您需要编辑帖子,请添加
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(params[:post])
redirect_to some_path and return
end
render 'edit' #error
end
编辑表单应向服务器发送PUT请求。 rails使用routes文件将url和请求(如GET / POST / PUT / DELETE)映射到控制器操作。
这里
PUT /posts/:id(.:format) posts#update
请求是PUT,控制器是PostsController,操作是更新。
也
post GET /posts/:id(.:format) posts#show
如果POST / PUT / DELETE,则需要从表单传递http请求。 你可以为'编辑'
这样做<%= form_for([@post,@comment],:url=>post_comment_path, :method => :put) do |f| %>
映射到PostsController的show请求。格式是html bydefault。有关详细信息,请详细查看服务器日志。