views:

111

answers:

1

I'm new to Rails so this is really basic and I'm sure I'm missing something simple. I'm trying to send some JSON to an action and get it to return a response in JSON. A simplified version of what I'm trying is below.

The jQuery I'm using:

var request = { 'voter': { 'voter_name': 'John', 'voter_email': '[email protected]'} };

var url = 'http://someip/Voters/create';

$.ajax({
    type: 'POST',
    url: url,
    data: request,
    success: function (data) { alert(data); },
    error: function (data) { alert(data); },
    dataType: 'json'
});

My action:

def create
    @voter = Voter.new(params[:voter])

    logger.info(@voter.to_json)

    render :json => @voter
end

It seems like this should be returning just fine, especially considering the console is showing the Voter object just fine:

Processing VotersController#create (for someip at 2010-08-17 21:19:51) [POST]  
Parameters: {"voter"=>{"voter_name"=>"John", "voter_email"=>"[email protected]"}}
{"voter":{"created_at":null,"updated_at":null,"voter_email":"[email protected]","voter_name":"John"}}
Completed in 11ms (View: 1, DB: 0) | 200 OK [http://someip/Voters/create]

The problem is that my alerts (or any other way I try to look at this data) are all showing me null. No object is being returned. Any pointers would be greatly appreciated.

A: 

I think you need to convert the instance to JSON before rendering. Like this:

render :json => @voter.to_json

Just like you do in your debug log output.

bjg
Thanks for the response. I tried that and it didn't seem to make a difference.
Jared