2013-03-13 97 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

相關問題