Thursday, 6 October 2011

Rendering an rjs partial from a controller action

I've recently been working on sharing some AJAXy controller actions between an admin and non-admin controller set up in completely different parts of a site, and this required the ability to use shared rjs templates. Tis is what I found out.

Lets say you originally have an erb and rjs template thus:

   # original update_widget.rjs
   page.replace_html "widget_wrapper", :partial => "widget"

   # original widget.erb
   <div id="widget_wrapper">
      lots of cool stuff here to show off your widget

You need to pull that rjs out into a partial template called _update_widget.rjs as below.

Note the full path-name for the partial - this is so we can share this template across controllers

   # new update_widget.rjs
   page << render(:partial => 'widgets/update_widget')

   # new partial: _update_widget.rjs
   page.replace_html "widget_wrapper", :partial => "widgets/widget"

Now to call an rjs template from a controller action you use the syntax as below:

Note: this is what you put in the new controller, the original controller (in this case it'd be widgets_controller) will still default to using the action-name to find the rjs template

   return render( :partial => 'widgets/update_widget.rjs') # the '.rjs' is essential

No comments: