Pass JavaScript variables to Rails controller 1
Google query doesn’t give much useful result on this topic. What we discuss here is if there is a value/function getParameters() in JavaScript returns "message = hello_world" (a URL query). How do you pass the JS variable into controller?
link_to_remote
Most common way is using link_to_remote which constructs an Ajax call, but the drawback is you have to handle the params[:message] using RJS template (or please let me know if I was wrong). Here is the example:
<%= link_to_remote "Create Post", :url => {:controller=>'posts', :action =>'new'}, :method => :post, :with =>"getParameters();" %>
As you see, the :with option will eventually become :with => "message=hello_world". A new parameter is accessible by calling params[:message]. But what if I only want to render another page?
capture block
Capture block captures a variable for the view which can be reused. The idea is to call the JavaScript inside capture block to pass it as a Rails variable in view. The @param variable is readable in the view.
<% @param = capture do %>
<%= javascript_tag "document.write(getParameter());" %>
<% end %>
link_to_function
Remember that we have already passed the JavaScript value to @param variable, it is used here. An inline redirect_to does the trick, that redirects to the new action and value is accessible by calling params[:message].
<%= link_to_function "Create Post" do |page|
page.redirect_to "/posts/new" + "?" + @param
end %>
I’m sure that you will have other ways of using these tricks in difference situation, but hope you get the idea and use them whenever is suitable.
Offline Rails Documentation
Although you can run gem server to have a rails rdoc running on localhost, the rdoc rails document could be troublesome to find a specific method you would like to know about. Fortunately, you may want to try out an ajax improved rails documentation:
- RailsBrain provides a free downloadable (free) offline documentation for rails. It has the lastest version 2.2.2 available for download. The ajax feature allows developer search method, class or file name via a input box. It’s a sufficient tool and I am using it now for development.
- Gotapi is an online API collections. you can manage/view/search all the API you are currently using in any languages(e.g. PHP, Java, .net and of course rails). Similar features are privided as RailsBrains, but it’s only available online.
Updates on March 24 2009
- Railsapi.com is a recent new project and is hosted on GitHub. It has better search capabilities. Intresting to note that it does not support Internet Explorer is currently (may be more specific version or not been IE tested). Apart from that, it’s smart, tidy and downloadable Rails doc.



