[英]Rails 3 respond_with json question
生成一些json有困難。 我試圖將一個活動記錄結果呈現給json,如下所示:
@data = User.find(1)
respond_with(@data, :include => :status)
json的結果是:
{
-user: {
address: null
email: "test@email.com"
first_name: "Test"
last_name: "Man"
status_id: 1
username: "testguy"
status: { }
}
}
所以有什么問題? 問題是:include =>:status似乎沒有帶來關系。 在我的用戶模型中,我有一個belongs_to:status。 如何讓這個在單個結果集上工作?
當我這樣做:
@data = User.where("id = 1")
respond_with(@data, :include => :status)
這種關系在json結果集中表現得很好。 但它在一個對象數組中,我不想要。
有任何想法嗎?
我假設您要包含的狀態不是http狀態代碼(200,201等)之一,也不是以任何方式與User對象關聯的對象,而是您自己的變量。
使用Rails 3.0.10和Ruby 1.9.2,您可能會發現這兩種解決方案中的一種適合您。 而不是respond_with
使用render
如下。
解決方案1
render :json => {:data => @data, :status => "whatever"}
json的結果是:
{
data:
{
user:
{
address: null
email: "test@email.com"
first_name: "Test"
last_name: "Man"
status_id: 1
username: "testguy"
}
}
status: "whatever"
}
解決方案2
render :json => {:user => {:address => @data.address, :email => @data.email, ..., :status => "whatever"}}
json的結果是:
{
user:
{
address: null
email: "test@email.com"
...
status: "whatever"
}
}
我希望這就是你要找的東西。
聽起來你在使用內置的導軌序列化時遇到了一些相同的痛苦。 我最終使用了RABL模板,這讓我的生活變得更輕松。 如果你需要一本關於快速啟動和運行RABL的指南,我會把它放在一起:
http://blog.dcxn.com/2011/06/22/rails-json-templates-through-rabl/
where
返回一個數組,因此您的結果是有意義的。 你where().first
需要where().first
或者因為它只是一個ID查找,所以只需使用find
。
這是很久以前的事了,但這仍然是最簡潔的答案:
@data = User.find(1)
respond_with(@data, :include => :status)
你現在可能已經解決了它的問題,但如果你還在使用probs,你可以這樣做嗎?
@data = User.find(1, :include => :status)
respond_to do |format|
format.json do
render @data.to_json(:include => :status)
end
end
如果這不起作用,您的關聯可能會出現問題。 關於'渴望加載協會'的api中有一個非常好的部分:
http://apidock.com/rails/ActiveRecord/Associations/ClassMethods
正如nixterrimus指出的那樣,RABL真的是要走的路。 它簡單,干凈,優雅。 我是相對較新的rails並沒有使用這些技術(to_json等)但是做了一些研究並實際使用RABL,我不禁想知道為什么它不是Rails的原生特性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.