1

I need to bring an array of ruby objects in JSON. I will need to find the item in the JSON object by id, so I think it is best that the id is the key of each object. This structure makes the most sense to me:

{
    "1":   {"attr1": "val1", "attr2": "val2"},
    "2":   {"attr1": "val1", "attr2": "val2"},
    "3":   {"attr1": "val1", "attr2": "val2"}
}

That way I can easily call into the json object like console.log(json_obj[id].attr1)

The issue is that I am not quite sure how to build this in ruby. This is as far as I have gotten:

# in ruby
@book_types = []
BookType.all.each do |bt|
   @book_types << {bt.id => {:attr => bt.attr}}
end
@book_types = @book_types.to_json

// In JS
var bookTypes = JSON.parse('<%=raw @book_types %>');

2 questions: How can I build this in ruby? Is there a better way to accomplish what I am doing?

Also just a note that I am building this on the Rails framework

Thanks!

1 Answer 1

10

Assuming BookType is an ActiveRecord class, you can just do this:

BookType.all(:select => "attr1, attr2").to_json

...where "attr1, attr2" is a list of the attributes you want to include in your JSON.

If you want the ids as keys, you can do this instead:

BookType.all.inject({}) { |hsh, bt|
  hsh[bt.id] = { "attr1" => bt.attr1, "attr2" => bt.attr2 }
  hsh
}.to_json
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.