Rails3 - Dirty Object Not Reporting?

So, I’m attempting to make sure that the associated user_id of an object
cannot be changed on update and I’m doing this with a before_update
callback and this method in the model:

before_update :lock_user_id

def lock_user_id
  if self.user_id_changed?
    self.user_id = self.user_id_was unless self.user_id_was == nil
  end
  true
end

but this spec fails:

it “user_id cannot be changed once QR has been created” do
@qr.update_attributes(:user_id => -1)
@qr.user_id.should == @user.id
end

at first I thought it was that update_attributes did not do a complete
save (not that i’ve ever enabled partial saves), but this alternate spec
also fails:

it “user_id cannot be changed once QR has been created” do
@qr.user_id = 99
@qr.save
@qr.user_id.should == @user.id
end

even stranger is that a method in another model which does the same
thing for another attribute passes its test.

Anybody have any idea what i’m doing wrong/alternate suggestions?

Thanks.

On Thu, Nov 4, 2010 at 6:30 AM, Gabriel S.
[email protected]wrote:

 true

save (not that i’ve ever enabled partial saves), but this alternate spec

Anybody have any idea what i’m doing wrong/alternate suggestions?

Thanks.

Only thing I could think of is validations for QR did not pass, which
means
that the before_update callback doesn’t get to be called at all.


Erol M. Fornoles
http://github.com/Erol
http://twitter.com/erolfornoles
http://ph.linkedin.com/in/erolfornoles

You guys were absolutely right, it wasn’t passing validations and was
not saved. Using update_attributes! demonstrated that, and I’m making
it a point to remember that.

Thanks to both of you!

Change @qr.update_attributes to @qr.update_attributes!, and I’ll bet you
see that @qr failed validations and never saved. I make it a habit to
always use update_attributes! in tests, so that a failure raises an
exception.

  • D

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs