开发者

Rails: update_attributes not updating all attributes

开发者 https://www.devze.com 2023-03-21 17:13 出处:网络
I have a simple model called Discussion which has a boolean column called resolved. In my form, I have the following code

I have a simple model called Discussion which has a boolean column called resolved.

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 can 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 开发者_开发技巧query doesn't include anything about updating that 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'm missing?


There are 4 reasons why this could be happening:

  1. resolved is already set to true in the database.
  2. You defined the resolved= method in your model and it no longer sets the attribute.
  3. You have attr_protected :resolved.
  4. You have attr_accessible but do not have :resolved in the list.


does your boolean column have a default? If it defaults to true - rails might not bother adding it to the set of attributes.

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


All,

I had recently begun rails and was taking over someone else's code and found another scenario that was not covered here that was getting me.

When using the style pointed to by this link, the params are formed in a separate method. I had to update the "_params" method to add it to the allowable list.

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


Are you sure that the element is sended it? I mean, form element without checked the element are not sended, so you have to put an hidden checkbox for default false.

0

精彩评论

暂无评论...
验证码 换一张
取 消