Easy updates in RJS

Posted by admin, Thu Jun 21 14:55:25 UTC 2007

Since I started programming in Ruby I’ve discovered that sometimes knowing how to do something is not the same thing as knowing how to do it right.

In the process of creating a fairly complex control for multi-select, I was struggling with an Ajax callback action, in which, among other things, I was trying to update a hidden field.  In RJS, when I want to update a field, I pull out the trusty page[‘hidden_field_id’].replace, and off I go.  But, I just couldn’t make it work in my Ajax callback, because I didn’t have access to the same instance variable that I had in the view when the hidden field was originally created.  And suddenly I’m diving into some really esoteric stuff, like define_method, because there’s gotta be a define_instance, doesn’t there?  Dead-ending there, I stumble into ActionView::Base::ObjectWrapper.new.  That’s gotta work, right?  Not really, at least I couldn’t quite figure it out.  I wasted an hour or so on this, and then wrapped up for the day.  On the drive home, I remembered reading about some RJS that could update the class of a DOM element.  Hmmm.  Sounds more promising.  Some Googling from home revealed this:

#3084 ([PATCH] Change css-class to DOM-elements in rjs) – Rails Trac – Trac

page[‘my_id’].className = ‘new_class_name’


And the brain-fart ended. I put away page.replace, and wrote:

page[‘hidden_field_id’].value = my_new _value

Which was what I was after, anyway.  Much simpler than replacing the entire DOM element.  Sigh.  When will I learn?  There’s ALWAYS a simpler way.

Filed Under: | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.