Ruby on rails 将ActiveRecord::Relation作为json返回到rails中的ajax调用
也许有一个简单的方法可以解决我的问题,但谷歌搜索却一无所获 我接到一个ajax电话:Ruby on rails 将ActiveRecord::Relation作为json返回到rails中的ajax调用,ruby-on-rails,ajax,json,activerecord,Ruby On Rails,Ajax,Json,Activerecord,也许有一个简单的方法可以解决我的问题,但谷歌搜索却一无所获 我接到一个ajax电话: $.get(path,{ section_id: "a", field_id: "b"}) .done(function(data) {alert(data);}) .fail(function() { alert("error"); }); 此ajax调用将转到指定的控制器并执行一个查询,该查询返回一个ActiveRecord::Relation对象。到目前为止,一切顺利。 现在,我要做的是将这个Act
$.get(path,{ section_id: "a", field_id: "b"})
.done(function(data) {alert(data);})
.fail(function() { alert("error"); });
此ajax调用将转到指定的控制器并执行一个查询,该查询返回一个ActiveRecord::Relation对象。到目前为止,一切顺利。
现在,我要做的是将这个ActiveRecord::Relation对象作为json返回给done函数。我该怎么做?
谢谢大家的帮助 我假设您希望从关系而不是活动记录类返回对象。在控制器中,应以适当的格式渲染对象,例如:
respond_to do |format|
format.json { render json: @your_object}
end
做这样的事
@post = Post.where(id: params[:id])
# @post at the moment is an AR::Relation
render json: @post, status: :ok
将实际返回序列化为JSON的记录。您可以通过执行以下操作,在rails控制台中实际测试这一点:
@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.
如果要返回ActiveRecord::Relation对象中使用的条件哈希,可以执行以下操作: @relation.where_value_hash.to_json