如何使用HTTP GET方法而不是POST来redirect_to或呈现新操作?

时间:2014-10-14 02:41:14

标签: ruby-on-rails ruby ruby-on-rails-4

我收到此错误:没有路由匹配[POST]“/ posts / 5 / comments / new”。

如何重定向到我的帖子/评论/新路线的GET操作(/posts/:post_id/comments/new(.:format))而不是POST?

以下是我对评论控制器的创建操作:

def create
   def create
      @post = Post.find(params[:post_id])
      @comment = @post.comments.create(comment_params)
      @comment.user_id = current_user.id #or whatever is you session name
    if @comment.save
      redirect_to @post
    else

      redirect_to new_post_comment_path
    end
      end
        end

如果您查看错误消息,您可以看到我的创建操作正在寻找我的new_post_comment_path路由的POST版本,因为它应该是GET。

rake路线的一些输出:

POST    /posts/:post_id/comments(.:format)  comments#create
new_post_comment_path   GET     /posts/:post_id/comments/new(.:format)  comments#new 

我如何做我的路线:

resources :posts do
  member do
    put "like", to: "posts#upvote"
    put "dislike", to: "posts#downvote"
  end
  resources :comments
end

评论_form.html.erb:

<%= form_for @comment, url: {action: "new"}, html: {class: "nifty_form"} do |f| %>

  <%= f.text_area :body, size: "40x12" %>
  <%= f.submit "Add Comment" %>
<% end %>

当我将操作从new更改为create时,我收到一条新的缺失模板错误消息:

缺少模板注释/创建,应用/创建{:locale =&gt; [:en],:formats =&gt; [:html],:variants =&gt; [],:handlers =&gt; [:erb,:builder,:raw,:ruby,:jbuilder,:coffee]}。搜索:*“app / views”*“。rvm / gems / ruby​​-2.1.2 / gems / devise-3.3.0 / app / views”

评论new.html.erb

<h1>New Comment</h1>
<%= render 'comments/form' %>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在RESTful环境中,您无法使用POST动词在控制器上达到“新”操作。如果您对路线感到困惑,请记住使用命令 rake routes ,直到您习惯它们为止。

无论如何,我都不太了解你的问题。如果你想重定向到新的动作,它将始终使用GET,所以它应该足够了:

redirect_to new_post_comment_path(@post)

我错过了什么吗?