Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails update_attribute isn't saving

I've run into a bizarre. I have a model GuardianUpdate with a field "read" which is a boolean. When I go to call update_attribute(:read, true) on a record, rails fails to actually update the record.

Here is my console output:

1.9.3p0 :026 > g = GuardianUpdate.find(1)
  GuardianUpdate Load (0.7ms)  SELECT `guardian_updates`.* FROM `guardian_updates` WHERE `guardian_updates`.`id` = 1 LIMIT 1
 => #<GuardianUpdate id: 1, update_id: 2, guardian_id: 11, read: true, created_at: "2012-04-21 04:06:45", updated_at: "2012-04-21 04:06:45"> 
1.9.3p0 :027 > g.update_attribute(:read, false)
   (0.3ms)  BEGIN
  Update Load (0.4ms)  SELECT `updates`.* FROM `updates` WHERE `updates`.`id` = 2 LIMIT 1
   (0.1ms)  COMMIT
 => true 
1.9.3p0 :028 > g.reload
  GuardianUpdate Load (0.5ms)  SELECT `guardian_updates`.* FROM `guardian_updates` WHERE `guardian_updates`.`id` = 1 LIMIT 1
 => #<GuardianUpdate id: 1, update_id: 2, guardian_id: 11, read: true, created_at: "2012-04-21 04:06:45", updated_at: "2012-04-21 04:06:45"> 
1.9.3p0 :029 > 

As you can tell, there is no UPDATE sql statement anywhere. Here's my GuaridanUpdate model:

class GuardianUpdate < ActiveRecord::Base
  belongs_to :update
  belongs_to :guardian
end

Any thoughts?

I should mention that update_column(:read, true) works, no problem at all.

like image 580
Matt De Leon Avatar asked Sep 02 '26 16:09

Matt De Leon


2 Answers

The belongs_to :update is creating an update accessor that is overwriting the internal rails method of the same name. That method is the one responsible for actually saving changes to an existant object.

Rename the association and you should be ok. Rails is suppose to raise a DangerousAttributeName exception to warn you of this - not sure why this isn't happening

like image 132
Frederick Cheung Avatar answered Sep 04 '26 11:09

Frederick Cheung


Since you have a "belongs_to :update", you probably have a model called Update. Some people have reported problems using a model called Update, see here:

https://rails.lighthouseapp.com/projects/8994/tickets/5772-calling-a-model-update-leads-to-unexpected-behavior

Maybe try renaming it to ContentUpdate or something else.

like image 21
coder_tim Avatar answered Sep 04 '26 13:09

coder_tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!