Rails: update_attributes does not update all attributes

I have a simple model called Discussion, which has a logical column called allowed.

In my form, I have the following code

<%= form_for(@discussion) do |d| %> ... <%= d.check_box :resolved %> <% end %> 

And in my controller, I have the following:

 def update @discussion = Discussion.find(params[:id]) if @discussion.update_attributes(params[:discussion]) etc... end end 

When I submit the form, I see that the parameters are being sent to the server ...

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"AsGsRHwiVva/+kTrBs0IjLeZwj1ZmXBuKZr9Pg/N6Xk=", "discussion"=>{"shortdesc"=>"Talk about something.", "content"=>"Try to update check box.", "resolved"=>"1"}, "commit"=>"Update Discussion", "id"=>"1"} 

But the request says nothing about updating this field.

 AREL (14.9ms) UPDATE "discussions" SET "content" = 'Try to update check box.', "updated_at" = '2011-07-18 17:53:50.783176' WHERE "discussions"."id" = 1 

Any idea on what I am missing?

+4
source share
4 answers

There are four reasons why this can happen:

  • resolved already installed in the database.
  • You have defined the resolved= method in your model and no longer set the attribute.
  • You have attr_protected :resolved .
  • You have attr_accessible but not listed :resolved .
+18
source

Does your boolean column have a default value? If true is used by default, the rails may not add it to the attribute set.

Alternatively, do you have attr_protected for this column? if so - rails will never add this field to the attributes using update_attributes. You will need to do this manually.

+1
source

Everything,

I recently started the rails and iterated over the code of another, and found another script that was not covered here that bothered me.

When using the style that this link points to, the parameters are formed in a separate method. I had to update the "_params" method to add it to a valid list.

http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

+1
source

Are you sure the item has been sent? I mean, the form element is not returned without checking the element, so you need to put a hidden checkbox for false by default.

0
source

All Articles