如何构建JSON对象?
目前我通过执行以下操作构建JSON对象:
@users = User.all @users.each do |user| @userlist < user.id, :fname => user.fname, :lname => user.lname, :photo => user.profile_pic.url(:small) } end
我的挑战是我现在想要包含来自@contacts
表的记录,这些记录具有与User
模型不同的字段集。
我试过了
@users = User.all @contacts = current_user.contacts @users << @contacts
但那没用。 将两个相似模型组合成一个JSON对象的最佳方法是什么?
json = User.all( :include => :contacts).to_json( :include => :contacts )
更新
对不起,让我为你正在做的事情提供一个更完整的答案……
@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
另一个更新
好的,所以忘了我 – 我度过了糟糕的一天,完全错过了你的问题。 您需要一些包含两个不相关数据集的JSON。 所有用户以及仅适用于当前用户的联系人。
你想为那个创建一个新的哈希,就像这样……
@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
@userlist = @users.map do |u| u.attributes.merge!(:contacts=>current_user.contacts) end json = @userlist.to_json