AnApprentice
AnApprentice

Reputation: 111080

Rails - JSON object with an array?

I'm able to create and send a JSON object like so:

  @mylist << {
    :id => item.id,
    :name => name.id
  }

render :json => { :result => 'success', :mylist => @mylist }

That works great. Problem I'm having now is that I need to include users with are 1 or more per item.

  @mylist << {
    :id => item.id,
    :name => name.id,
    :users => item.users
  }

Where item.users contains a list of (user.id, user.name, user.desc).

how do I include an array like users inside a json object? How to build in Rails and then how to parse it with jQuery?

Thanks

UPDATE

the code above is inside a:

@items.each_with_index do |item, i|
end

Perhaps that is a problem here?

Upvotes: 0

Views: 2110

Answers (2)

iain
iain

Reputation: 16284

This should work fine out of the box. Arrays inside arrays is no problem. Rails walks down your objects and tries to convert them to simple objects like hashes, arrays, strings and numbers. ActiveRecord objects will turn all their attributes into a hash when you convert it to JSON. If item.users is an array of ActiveRecord instances, than your example will automatically work. You can retrieve them in Javascript exactly as you would walk through a hash and array in Ruby. So something like:

response['mylist']['users'][0]['name']

Edit

To limit the fields in the user, add a method to the user class:

class User < ActiveRecord::Base
  def as_json(*)
    { :name => name, :desc => desc }
  end
end

Upvotes: 0

Skilldrick
Skilldrick

Reputation: 70889

If items.users is an array then it will be rendered as a JSON array.

When you get the JSON response in your JavaScript, you'll just need to loop over the array:

for (var i = 0; i < data.users.length; i++) {
    //do something with data.users[i]
}

where data is the JSON data returned from the Ajax call.

Upvotes: 1

Related Questions