我在學習Rails 4時通過一個小練習,但嘗試更新對象時遇到路由錯誤。我不斷收到一條錯誤消息:沒有路由匹配[POST] 「/電影/ 1 /編輯」,但不能看到我的代碼是不正確的:Rails 4 RoutingError:No Route Matches [POST]
我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
這將是我的猜測,以及,空白行動將回發到這是編輯路徑 – Doon
感謝@meager的current_url,但現在我得到一個''NoMethodError在電影#編輯:未定義的方法'movie_path'爲#<#:0x007ff4c99f6300>''? –
TomK
你還沒有命名你的路線。你需要使用'get「movies =>」movies#index「,如:」movies「',或者正確的東西,只需要拋棄所有的路線,並使用'resources:movies'。 – meagar