Reputation: 147
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.
Upvotes: 6
Views: 15292
Reputation: 123
You may also want to make sure your url:
path is singular on the @form_form
.
Upvotes: 0
Reputation: 1459
I got myself in a similar situation today with a mismatched resource and model name. I agree the model and controller names need to correlate, but you can override the routes name to be whatever you want.
resources :cars, path: "adverts"
Along with RESTful routing
<%= form_for @car do |f| %>
Upvotes: 0
Reputation: 8604
If you used RESTful routing, you don't need to specify a url
, just need:
<%= form_for @car do |f| %>
The form can know @car
is new record, or saved record, so it will send 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
Upvotes: 4
Reputation: 43298
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.
Upvotes: 15