How do I build a JSON object?

后端 未结 2 609
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 10:16

Currently I build a JSON object by doing:

@users = User.all

@users.each do |user|
  @userlist << {
    :id => user.id,
    :fname => user.fname,
            


        
相关标签:
2条回答
  • 2021-01-31 11:01
    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, and the contacts just for the current user.

    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
    
    0 讨论(0)
  • 2021-01-31 11:10
      @userlist = @users.map do |u|
        u.attributes.merge!(:contacts=>current_user.contacts)
      end
      json = @userlist.to_json
    
    0 讨论(0)
提交回复
热议问题