Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving updates to objects in rails

I'm trying to update one of my objects in my rails app and the changes just don't stick. There are no errors, and stepping through with the debugger just reveals that it thinks everything is updating.

Anyway, here is the code in question...

  qm = QuestionMembership.find(:first, :conditions => ["question_id = ? AND form_id = ?", q_id, form_id])
  qm.position = x
  qm.save

For reference sake, QuestionMembership has question_id, form_id, and position fields. All are integers, and have no db constraints.

That is basically my join table between Forms and Questions.

Stepping through the code, qm gets a valid object, the position of the object does get changed to the value of x, and save returns 'true'.

However, after the method exits, the object in the db is unchanged.

What am I missing?

like image 899
CJ F Avatar asked Mar 14 '09 21:03

CJ F


4 Answers

You may not be finding the object that you think you are. Some experimenting in irb might be enlightening.

Also, as a general rule when changing only one attribute, it's better to write

qm.update_attribute(:position, x)

instead of setting and saving. Rails will then update only that column instead of the entire row. And you also get the benefit of the data being scrubbed.

like image 124
user37011 Avatar answered Nov 19 '22 13:11

user37011


Is there an after_save?

Is the correct SQL being emitted?

like image 27
wombleton Avatar answered Nov 19 '22 13:11

wombleton


In development log, you can actually see the sql that is generated.

For something like this:

qm = QuestionMembership.find(:first, :conditions => ["question_id = ? AND form_id = ?", q_id, form_id])
qm.position = x
qm.save

You should see something to the effect of:

SELECT * FROM question_memberships WHERE question_id=2 AND form_id=6 LIMIT 1
UPDATE question_memberships SET position = x WHERE id = 5

Can you output what sql you are actually seeing so we can compare?

like image 25
XGamerX Avatar answered Nov 19 '22 13:11

XGamerX


Either update the attribute or call:

qm.reload

after the qm.save

like image 1
andres Avatar answered Nov 19 '22 15:11

andres