Pages

Saturday, September 17, 2011

Snippets on my rails 3 ujs study.

Once I get the hang of things, I should look to publishing a proper tutorial/article on how UJS works with Rails 3.

For the moment, these are just notes to self.


For javascript responses (ie. use of ajax), rails will render whatever is inside the 
<controller>/<action>.js.erb file.
This corresponds with the explicit respond_to :js {} block within each controller method.


If the desired action.js.erb file is to be rendered,
1) the action in the controller method must call it explicitly by having a .js block.

Example:

  # DELETE /parts/1
  # DELETE /parts/1.xml
  def destroy
    @part = Part.find(params[:id])
    @part.destroy
    respond_to do |format|
      format.html { redirect_to(parts_url) }
      format.xml  { head :ok }
    format.js   {
      # it could be blank but we explicitly tell rails to render the destroy.js.erb file's contents
    }
    end
  end

2) the javascript codes that does the fading out of a deleted object which used to reside in application.js will be moved to action.js.erb (after all, we want to put action specific javascript code into their own js.erb file)

$('.delete_part').bind('ajax:success', function() {
$(this).closest('tr').fadeOut();
});


BUT if we wanted to have the javascript codes (that do the fading) on an application javascript level (application.js.erb), 
1) the action method in the controller DOES NOT NEED to explicitly return via :js 
(ie. no need for the :js block)
2) no action.js.erb file required