Update form in rails - No route matches [PUT]

Stack Stack picture Stack Stack · Nov 30, 2012 · Viewed 14.1k times · Source

I have a form to create adverts.

Controllers:

  def edit
    @engines = Engine.all
    @car = Car.find(params[:id])
  end

  def update
    @car = Car.find(params[:id])

    if @car.save
      redirect_to root_path
    end
  end

My routes:

resources :adverts

Create.html.erb

<%= form_for @car, :url => adverts_path do |f| %>

  <div><%= f.label :name %><br />
  <%= f.text_field :name %></div>

  <%= hidden_field_tag :model_id, params[:model_id] %>

  <%= select_tag :engine_id, options_from_collection_for_select(@engines, "id", "name",:selected=>@car.engine_id) %>

  <div><%= f.submit "Create car!" %></div>
<% end %>

I can create advert, but I can't to update it.

edit.html.erb

<%= form_for @car, :url => adverts_path do |f| %>

  <div><%= f.label :name %><br />
  <%= f.text_field :name %></div>

  <%= hidden_field_tag :model_id, params[:model_id] %>

  <%= select_tag :engine_id, options_from_collection_for_select(@engines, "id", "name",:selected=>@car.engine_id) %>

  <div><%= f.submit "Update car!" %></div>
<% end %>

when I submited my form, I have an error - No route matches [PUT] "/adverts"

$ rake routes:

                       adverts GET    /adverts(.:format)                     adverts#index
                               POST   /adverts(.:format)                     adverts#create
                    new_advert GET    /adverts/new(.:format)                 adverts#new
                   edit_advert GET    /adverts/:id/edit(.:format)            adverts#edit
                        advert GET    /adverts/:id(.:format)                 adverts#show
                               PUT    /adverts/:id(.:format)                 adverts#update
                               DELETE /adverts/:id(.:format)                 adverts#destroy

I need help.

Answer

Mischa picture Mischa · Nov 30, 2012

When you are updating you have to let Rails know which object you want to update by passing an id.

In edit.html.erb change:

<%= form_for @car, :url => adverts_path do |f| %>

to:

<%= form_for @car, :url => advert_path(@car) do |f| %>

By the way, I find your code very strange. Why don't your model names match your controllers and routes? I mean you are creating an advert but your model is called car. That doesn't make any sense. Either call it car or advert, but don't mix them.