Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 RoutingError: No Route Matches [POST]

I'm working through a small exercise while learning Rails 4, but running into a routing error while trying to update an object. I keep getting an error message: No route matches [POST] "/movies/1/edit" but can't see where my code is not correct:

my 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

Here's my 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" %>    

and the routes.rb file:

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

last, here's the output from running 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
like image 698
TomK Avatar asked Oct 21 '13 17:10

TomK


2 Answers

form_for @movie.name should be form_for @movie. I can't tell what's going on, but I suspect this is somehow giving you a <form action="">.

like image 191
meagar Avatar answered Oct 04 '22 23:10

meagar


in index file if you are using

button_to 'Edit', edit_movie_path(movie)

change it to

link_to 'Edit', edit_movie_path(movie)

because button send it as POST but the link will send it as GET.

like image 24
sultan alsamaani Avatar answered Oct 05 '22 00:10

sultan alsamaani