Ruby-on-rails 如何构建 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5863477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I build a JSON object?
提问by AnApprentice
Currently I build a JSON object by doing:
目前我通过执行以下操作来构建 JSON 对象:
@users = User.all
@users.each do |user|
@userlist << {
:id => user.id,
:fname => user.fname,
:lname => user.lname,
:photo => user.profile_pic.url(:small)
}
end
My challenge is I now want to include records from the @contactstable that have a different set of fields than the Usermodel.
我的挑战是我现在想要包含@contacts表中与User模型具有不同字段集的记录。
I tried doing
我试着做
@users = User.all
@contacts = current_user.contacts
@users << @contacts
But that did not work. What's the best way to combine two similar models into one JSON object?
但这没有用。将两个相似的模型组合成一个 JSON 对象的最佳方法是什么?
回答by smathy
json = User.all( :include => :contacts).to_json( :include => :contacts )
Update
更新
Sorry, let me give a more complete answer for what you're doing...
对不起,让我对你在做什么给出一个更完整的答案......
@users = User.all( :include => :contacts )
@userlist = @users.map do |u|
{ :id => u.id, :fname => u.fname, :lname => u.lname, :photo => u.profile_pic.url(:small), :contacts => u.contacts }
end
json = @userlist.to_json
Another Update
另一个更新
Ok, so just forget me - I was having a bad day and totally missed the point of your question. You want some JSON that includes two unrelated sets of data. All the users, andthe contacts just for the current user.
好吧,忘了我吧——我今天过得很糟糕,完全没有抓住你问题的重点。您需要一些包含两组不相关数据的 JSON。所有用户,以及当前用户的联系人。
You want to create a new hash for that then, something like this...
你想为此创建一个新的哈希,就像这样......
@users = User.all
@userlist = @users.map do |u|
{ :id => u.id, :fname => u.fname, :lname => u.lname, :photo => u.profile_pic.url(:small) }
end
json = { :users => @userlist, :contacts => current_user.contacts }.to_json
回答by user1008580
@userlist = @users.map do |u|
u.attributes.merge!(:contacts=>current_user.contacts)
end
json = @userlist.to_json

