如何构建JSON对象?

AnA*_*ice 20 ruby ruby-on-rails ruby-on-rails-3

目前我通过执行以下操作构建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
Run Code Online (Sandbox Code Playgroud)

我的挑战是我现在想要包含@contacts表中具有与User模型不同的字段集的记录.

我试过了

@users = User.all
@contacts = current_user.contacts
@users << @contacts
Run Code Online (Sandbox Code Playgroud)

但那没用.将两个相似模型组合成一个JSON对象的最佳方法是什么?

sma*_*thy 49

json = User.all( :include => :contacts).to_json( :include => :contacts )
Run Code Online (Sandbox Code Playgroud)

更新

对不起,让我为你正在做的事情提供更完整的答案......

@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
Run Code Online (Sandbox Code Playgroud)

另一个更新

好的,所以忘记我 - 我度过了糟糕的一天,完全错过了你的问题.您需要一些包含两个不相关数据集的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
Run Code Online (Sandbox Code Playgroud)


小智 5

  @userlist = @users.map do |u|
    u.attributes.merge!(:contacts=>current_user.contacts)
  end
  json = @userlist.to_json
Run Code Online (Sandbox Code Playgroud)

  • 解释这是如何回答这个问题本来是很好的. (3认同)