Rails 4 路由错误:没有匹配的路由[POST]

10

我在学习Rails 4时正在进行一个小练习,但是在尝试更新对象时遇到了路由错误。我一直收到错误消息:没有匹配路由[POST]"/movies/1/edit",但是无法看到我的代码有什么不正确之处:

我的movies_controller.rb

class MoviesController < ApplicationController

  def index
    @movies = Movie.all
  end

  def show
    @movie = Movie.find(params[:id])
  end

  def new
    @movie = Movie.new
  end

  def create
    @movie = Movie.create(movie_params)

    if @movie.save 
        redirect_to "/movies/#{@movie.id}", :notice => "Your movie was saved!"
    else
        render "new"
    end
  end

  def edit
    @movie = Movie.find(params[:id])
  end

  def update
    @movie = Movie.find(params[:id])

    if @movie.update_attributes(params[:movie])
        redirect_to "/movies"
    else
        render "edit"
    end
  end

  def destroy

  end


  private

  def movie_params
    params.require(:movie).permit(:name, :genre, :year)
  end
end

这是我的edit.html.erb文件

<h1>Now Editing:</h1>

<h3><%= @movie.name %></h3>

<%= form_for @movie.name do |f| %>

<%= f.label :name %>
<%= f.text_field :name %>
<br>
<%= f.label :genre %>
<%= f.text_field :genre %>
<br>
<%= f.label :year %>
<%= f.number_field :year %>
<br>
<%= f.submit "Update" %>    

和 routes.rb 文件:

MovieApp::Application.routes.draw do

  get "movies"             => "movies#index"
  post "movies"            => "movies#create"
  get "movies/new"         => "movies#new"
  get "movies/:id"         => "movies#show"
  get "movies/:id/edit"    => "movies#edit"
  put "movies/:id"         => "movies#update"

end

最后,这是运行rake routes的输出结果:

    Prefix Verb URI Pattern                Controller#Action
    movies GET  /movies(.:format)          movies#index
           POST /movies(.:format)          movies#create
movies_new GET  /movies/new(.:format)      movies#new
           GET  /movies/:id(.:format)      movies#show
           GET  /movies/:id/edit(.:format) movies#edit
           PUT  /movies/:id(.:format)      movies#update
3个回答

4

form_for @movie.name 应该修改为 form_for @movie。我不确定具体情况,但我怀疑这可能是导致你得到一个 <form action=""> 的原因。


这应该是我的猜测,空白操作将会提交到当前URL,即编辑路径。 - Doon
谢谢@meager,但我现在遇到了一个问题:“在Movies#edit中出现NoMethodError错误:undefined method `movie_path' for #<#Class:0x007ff4cb263e38:0x007ff4c99f6300>”。 - TomK
你还没有为你的路由命名。你需要使用 get "movies" => "movies#index", as: "movies" 或者更好的方式是,放弃所有的路由,只使用 resources :movies - user229044
没有命名路由是问题所在,@meager,谢谢。我知道我可以把“resources:movies”放到我的“routes.rb”文件中,但我想手动完成它,以了解路由的工作原理。再次感谢~ - TomK

2

你的错误信息显示你正在向编辑URL发送POST请求。

没有匹配路由 [POST] "/movies/1/edit"

但是在路由中,你指定了一个GET请求。

get "movies/:id/edit" => "movies#edit"

我认为这可能会导致问题,所以你可以将请求更改为POST。

post "movies/:id/edit"    => "movies#edit"

1
那不是真正的问题。你应该“获取”编辑表单,然后将更改后的资源POST / PUT回去。将编辑改为POST会破坏这一流程,而且不是正确的做法。 - Doon
2
他的路由没问题,他绝对不应该修改路由以接受错误的方法。这只会给他带来另一个 bug,而他的路由肯定永远无法到达需要到达的 movies#update - user229044

1
在索引文件中,如果你正在使用


button_to 'Edit', edit_movie_path(movie)

将其改为:

改为

link_to 'Edit', edit_movie_path(movie)

因为按钮将其发送为POST,但链接将其发送为GET

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接