Reputation: 21603
In my API, I am converting an ActiveRecord object into json via:
user.to_json :methods => :new_messages
Using irb, when I execute this statement, I get:
{someAttr: someValue, ....}
which is perfect. This is a single object so it's not wrapped in an array. Now when I run this in sinatra app like this:
get '/api/users/:fb_id' do |fb_id|
user = User.where :fb_id => fb_id
user.to_json :methods => :new_cookies
end
It wraps it in an array!!! Like this:
[{someAttr: someValue, ....}]
How can I fix this, and more importantly, why?!?
Upvotes: 2
Views: 398
Reputation: 5688
replace this line:
user = User.where :fb_id => fb_id
with this line:
user = User.find_by_fb_id fb_id
Upvotes: 1
Reputation: 510
Simply using Hash.[]
Hash[{a: :b}]
# => {:a=>:b}
and more importantly, why?!?
Which ORM are you using in the second example? If it's ActiveRecord, then User.where :fb_id => fb_id
returns ActiveRecord::Relation object which wraps into an array when you call .to_json
. It can be fixed like so
get '/api/users/:fb_id' do |fb_id|
user = User.find_by_fb_id(fb_id)
user.to_json :methods => :new_cookies
end
Upvotes: 1