AnApprentice
AnApprentice

Reputation: 110950

How do I build a JSON object?

Currently I build a JSON object by doing:

@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 @contacts table that have a different set of fields than the User model.

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?

Upvotes: 21

Views: 51018

Answers (2)

user1008580
user1008580

Reputation: 71

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

Upvotes: 5

smathy
smathy

Reputation: 27961

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

Upvotes: 49

Related Questions