Sunday, May 1, 2011

Rails 3 Unobtrusive Javascript is Unintuitve

So what I wanted to do was link from a partial view to a controller method through a route which took a title parameter and from the controller method run a javascript file in order to append content to a div with a unique name defined by the title param.
In django it's pretty straightforward, but ruby on rails 3 had me scratching my head for a good long while.
Here's the solution, or at least the parts that were difficult:
the link:

<%= link_to "Comments", show_comments_path( :format => 'js', :comment_id=> session[:id] ), :remote => true %>
This whole :remote => true business tells rails 3 that this is an ajax call. The :format param does NOT get passed into the url, but DOES render the response as html, most of the time. Which is to say, rails will run the .js.erb file with the name matching your route.
Here's the route:
match 'show_comments/:comment_id', :to => 'deals#show_comments', :as => :show_comments
So first rails runs the show_comments method from the appropriate controller, which you can use to set state variables for the javascript. Then, whatever is in show_comments.js.erb will be run, and the current page will NOT be reloaded or redirected. No partial needed. No view needed. The controlling method will do all of this as the default return, so no return or render needed either, only the .js.erb file which has your prototype or jquery calls, or whathaveyou.
facepalms: 4 (steady, slow, only slightly infuriating progress)

1 comment:

  1. Unobstrusive javascript was created to work with ajax calls in context of rails application. There is no need to serialize form, send it to controller, get json, get validation parameters, set validation prameters and etc. All what you need is to move your form out of the view into partial and the makre replaceWith to change you form after submit button was pressed.
    If you can't understand the basics then think about to change the proffession.