mrudult
mrudult

Reputation: 2570

Rails update method for updating records not working

I have two methods in PersonsController- edit and update and a Person model:

def edit
  @person=Person.find(params[:id])
end

def update
    @person=Person.find(params[:id])
    @person.update_attributes(params[:person])
end  

and my edit.html.erb:

<h2> Edit info here!</h2>
<%= @person.name %>

<%= form_for @person, html: {mulitpart: true}  do |f| %>
  <p><%= f.text_field :location %></p>
  <p><%= f.submit :submit , class: "btn btn-large btn-success" %></p>
<% end %>  

and routes.rb:

resources :persons

But when I submit the form I get:

AbstractController::ActionNotFound
The action '5231d2491dba7fb057000004' could not be found for PersonsController

The 5231....... is id of a person.

Request Parameters:

{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"3TL7nn4UxhxFoxETeooBMThhkE0VdMoGFpjN9sx4srk=", "person"=>{"location"=>"nagpur"}, "commit"=>"submit", "controller"=>"persons", "action"=>"5231d2491dba7fb057000004"}

What is wrong here? I'm using mongoid and rails 3.2.13.

Upvotes: 3

Views: 5639

Answers (1)

Billy Chan
Billy Chan

Reputation: 24815

Your final comment reveals the source of error.

For either #edit or #update, you should not set the params manually in hidden field, which is also unnecessary.

If using conventional RESTful routes as resources :persons, you edit route will look like GET /persons/1/edit where 1 is the param id. You can get this person in #edit as

@person = Person.find(params[:id])

Similarly, you can get the person again in #update whose route is PUT persons/1

@person = Person.find(params[:id])

Then the question is answered.

But there is one more problem in your code, the part you get the attributes for updating. Because the params of person's attributes are sent via form, all attributes are under params[:person]. Thus, to get the photo attribute, you should use

params[:person][:photo] # Not params[:photo]

Upvotes: 1

Related Questions