Rails ActiveRecord update_attributes! doesn't work
My used envs are listed below:
Mysql: 5.1.51-community MySQL Community Server
Rails: 2.3.5
Ruby: 1.8.7
There is one record i got is item, then i used the code below to update attributes,
item.update_attributes!(
:a => a,
:b => b,
:c => c
)
for all those updated attributes only field a value is changed, other attributes values keep not changed, but i don't know which attributes are changed, so i updated all attributes.
During debug process, i found that field a value is changed and that's different from record item's a value, but update doesn't have any effect.
Does somebody can give me help? thank you.
Added:
Just now i trace into rails code, and found that the issue is related with rails code here:
def update(attribute_names = @attributes.keys)
quoted_attribute开发者_如何学JAVAs = attributes_with_quotes(false, false, attribute_names)
return 0 if quoted_attributes.empty?
connection.update(
"UPDATE #{self.class.quoted_table_name} " +
"SET #{quoted_comma_pair_list(connection, quoted_attributes)} " +
"WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quote_value(id)}",
"#{self.class.name} Update"
)
end
if i changed the field a value in db to empty, then attribute_names is an array containing field a, but the field a value in db is not empty, the attribute_names is an empty array, but @attributes is always a map containing a, b and c. confused after seeing rails code.
Sorry there's not enough information in the question to go on, so this is just speculation:
Any chance you're using attr_accessible
or attr_protected
with this model?
Using attr_accessible
and it doesn't include b and c, or attr_protected
and it includes b and c would explain the behaviour you're seeing.
If this is the case you will have to make multiple update_attribute! calls.
I found the cause, since the method to change the field value has errors, after changing, its original and new value are the same, so AR doesn't do update action since there is no any field is changed.
精彩评论