2013-03-13 29 views
0

对于我的问题,可能有一个简单的解决方案,但密集的Google搜索没有提供任何内容。将ActiveRecord :: Relation作为json返回到rails中的ajax调用

我有一个Ajax调用:

$.get(path,{ section_id: "a", field_id: "b"}) 
.done(function(data) {alert(data);}) 
.fail(function() { alert("error"); }); 

这个Ajax调用转到指定的控制器和执行查询的返回一个ActiveRecord :: Relation对象。到现在为止还挺好。 现在,我想要做的是将这个ActiveRecord :: Relation对象作为json返回到done函数。我怎样才能做到这一点? 感谢所有的帮手!

回答

1

我假设你想从一个关系而不是活动记录类返回一个对象。在你的控制器,你应该使你的对象在适当的格式,是这样的:

respond_to do |format| 
    format.json { render json: @your_object} 
end 
0

做这样

@post = Post.where(id: params[:id]) 
# @post at the moment is an AR::Relation 
render json: @post, status: :ok 

东西实际上将只返回序列化为JSON记录。您可以通过以下操作中轨控制台实际测试了这一点:

@record = YourModel.where(some_condition: some_parameter) 
@record.class #=> ActiveRecord::Relation 
@json_record = @record.to_json 
@json_record.class #=> String 
# @json_record will be the JSON representation of whatever the Relation fetched for you. 
1

如果你想返回的的ActiveRecord :: Relation对象,你可以做到这一点的散列使用的标准:

@relation。 where_values_hash.to_json

相关问题