«

»

Aug 14

Nifty Rails tricks

Two new things I’ve learned today (not that these are news to the cognoscenti, but I am always looking for new ideas to write down so I can remember them)

  • in_place_editor_field
  • {:onchange => "#{remote_function(:url  => {:action => "update_degree_and_major_based_on_mods"}, :with => "'mods='+value")}"}

in_place_editor_field

  • Basically, it sets up your form fields with Javascript so you can click on them, edit them and have the edits saved back to the database.  Pretty nifty!
    • Looking at the javascript source, there’s some serious mojo going on underneath the covers – new Ajax.InPlaceEditor( field_to_edit, controller_method_to_call_with_object_id, mysterious_callback_function)
      • The callback function is the part that I am confused about, but that’s a topic for another day.

remote_function

  • Two parts – the invocation and the controller
  • The invocation is straightforward enough to follow:
    • onchange="new Ajax.Request('/applications/update_degree_and_major_based_on_mods', {asynchronous:true, evalScripts:true, parameters:'mods='+value + '&authenticity_token=' + encodeURIComponent('token')})
      • make an Ajax request to the specified controller, asynchronously, and with a particular parameter to drive the change
  • The controller is clever


mods = Modus.find_by_mods(params[:mods])
@captain = Captain.find(mods.captain_id)
@dinghy = Dinghy.find(mods.dinghy_id)
render :update do |page|
page.replace_html 'dinghy_info', :partial => 'dinghies/dinghy', :objects => @dinghy
page.replace_html 'captain_info', :partial => 'captains/captain', :objects => @captain
end

This looks up the object from the parameter, finds associated objects, and then calls this page.replace_html function, which replaces the contents of a <div> with a completely different div, as described by the appropriate partial template.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>