Update form in rails - no route matches [PUT]

I have a form for creating ads.

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 an ad, but I can’t 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 submitted my form, I have an error - There are no links to the route [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.

+4
source share
3 answers

When you update, you must let Rails know which object you want to update by passing id .

In edit.html.erb change:

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

in

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

By the way, I think your code is very strange. Why don't your model names match your controllers and routes? I mean, you create ads, but your model is called a car. It makes no sense. Or call it a car or an advertisement, but don't mix them.

+14
source

If you used RESTful routing, you do not need to specify a url , you just need to:

 <%= form_for @car do |f| %> 

The form may know that @car is a new record or a saved record, so it will send the appropriate http method.

And in your update action:

 def update @car = Car.find(params[:id]) if @car.update_attributes(params[:car]) redirect_to root_path end end 
+4
source

Today I found myself in a similar situation with an inappropriate resource and model name. I agree that the model and controller names should correlate, but you can redefine the route name as you like.

 resources :cars, path: "adverts" 

Along with RESTful routing

 <%= form_for @car do |f| %> 
0
source

All Articles