rails

json and rails

Posted in javascript, jquery, rails on February 20th, 2010 by paul – Be the first to comment

The following is one way to handle json responses from a rails application.
So, I have a ajax request in a script in my page. In this example I am using the jquery poll plugin to poll the status of a file import.

$("#<%=import.id%>").poll({
    url: "/mis_imports/import_state/<%=import.id%>",
    interval: 3000,
    type: "GET",
    success: function(data){
                   var return_data = eval('(' + data + ')');
                   $("#<%=import.id%>").attr("class","mis_import_state_"+return_data.state);
		   $("#<%=import.id%>_message").html(""+return_data.status+"");
		   $("#<%=import.id%>_timestamp").html(""+return_data.timestamp+"");
		   if (return_data.state == 1){
		     $(this).stop();
		   }
    }
});

And on the server, my rails action method looks like this:

def import_state
    import = MisImport.find(params[:id])
    render :text => {:state => import.state,:status => import.message,:timestamp => Time.now.strftime("%d:%b:%Y %H:%M:%S")}.to_json
  end

The key part to this working is line 6 of the javascript listing, where one ‘evals’ the data returned from the server.
This effectively rehydrates the data structure into a usable javascript object, and that’s the bit I keep forgetting!

There are probably smarter ways of doing this; I know there is a jQuery.getJSON() function, but in this case I couldn’t work out how to use that with jquery poll. Again, probably very simple…

error undefined method `use_transactional_fixtures=’ for Test::Unit::TestCase:Class

Posted in rails on September 16th, 2009 by paul – Be the first to comment

When running some tests today I hit the error message: undefined method `use_transactional_fixtures=’ for Test::Unit::TestCase:Class

Searching for this came up with numerous results.

The way to fix this is to change the class in test/test_helper.rb from Test::Unit::TestCase to ActiveSupport::TestCase

Tests should run properly now.

This is while using rails 2.3.2 on OS X.

using custom routes to pass parameters to a method

Posted in rails on August 3rd, 2009 by paul – Comments Off

In an application I am working on I needed to pass the ID of an object to the new action of a controller. This ID was the id of an object the new object would be linked to.

Now creating the link as /controller/object_id called the show method (as this is a standard restful route). What I wanted to do was do something like /controller/new/object_id , but that isn’t a valid route.

What I had to do was create a custom route to make this work.

So in my routes.rb file I added a line like this:

map.new_object '/controller/new/:object_id', :controller => 'controller', :action => 'new'

now in my new action I can access the passed in id as params[:object_id]