John On Rails

Saturday, August 16, 2008

Tips That'll Save You Time...

flash
Are you flash messages NOT showing up? Learn flash[:notice] and flash.now[:notice].

need to pass messages from controller to view from ajax calls
Learn page[:div_id].replace_html... a life saver

need to return more that 1 object from a method call?
Don't forget(I did), ruby can do this easily: 

def index
  @object1, @object2 = method(arg1, arg2)
end

...

def method(arg1, arg2)
  ..
  return object1, object2
end

Saturday, June 7, 2008

before_save catch 22

I was attempting to update an attribute in my model using a value from a foreign key. I was not updating to what I was telling it to update to. So, I dove into the console to see what was happening. It turns out I was setting the code BACK to its original value in the before_save method. Not the behaviour I expected, because I didn't read the docs:

"Is called BEFORE Base.save"

# this hoses up the build_promotion process in the preferences screen,
# but it is needed for adding and updating kids... catch 22
person.promotion_sequence = person.room.promotion_sequence

So, my value was getting overwritten by the old value. So, I commented out that line of code.

# person.promotion_sequence = person.room.promotion_sequence

Now, I hit my next problem. I went to update my record using an existing form via the update_attributes method. This did not work because the attribute that needed to be updated was NOT in the params. So, here is how I fixed it :

@person.room_id = params[:person][:room_id]
@person.promotion_sequence = @person.room.promotion_sequence
@person.promotion_grade = @person.room.max_age_grade
@person.update_attributes(params[:person])

This now persists the promotion_grade. I'm not so certain this is the correct way to doing it.