简体   繁体   English

为什么ruby on rails返回null而不是json对象

[英]Why is ruby on rails returning null instead of json object

I'm new to Rails so this is really basic and I'm sure I'm missing something simple. 我是Rails的新手,所以这真的很基础,我敢肯定我缺少一些简单的东西。 I'm trying to send some JSON to an action and get it to return a response in JSON. 我正在尝试向操作发送一些JSON,并使其返回JSON中的响应。 A simplified version of what I'm trying is below. 下面是我正在尝试的简化版本。

The jQuery I'm using: 我正在使用的jQuery:

var request = { 'voter': { 'voter_name': 'John', 'voter_email': 'john@john.com'} };

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: 似乎应该返回的还不错,特别是考虑到控制台显示的Voter对象还不错:

Processing VotersController#create (for someip at 2010-08-17 21:19:51) [POST]  
Parameters: {"voter"=>{"voter_name"=>"John", "voter_email"=>"john@john.com"}}
{"voter":{"created_at":null,"updated_at":null,"voter_email":"john@john.com","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. 任何指针将不胜感激。

I think you need to convert the instance to JSON before rendering. 我认为您需要在渲染之前将实例转换为JSON。 Like this: 像这样:

render :json => @voter.to_json

Just like you do in your debug log output. 就像在调试日志输出中一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM