在我的 API 中,我通过以下方式将 ActiveRecord 对象转换为 json:
user.to_json :methods => :new_messages
使用irb,当我执行这个语句时,我得到:
{someAttr: someValue, ....}
这是完美的。这是一个单个对象,因此它没有包装在数组中。现在,当我在 sinatra 应用程序中运行它时,如下所示:
get '/api/users/:fb_id' do |fb_id|
user = User.where :fb_id => fb_id
user.to_json :methods => :new_cookies
end
它将它包装在一个数组中!!!像这样:
[{someAttr: someValue, ....}]
我该如何解决这个问题,更重要的是,为什么?!?
最佳答案
只需使用 Hash.[]
Hash[{a: :b}]
# => {:a=>:b}
and more importantly, why?!?
您在第二个示例中使用哪个 ORM?如果是 ActiveRecord,则 User.where :fb_id => fb_id
返回 ActiveRecord::Relation当您调用 .to_json
时,该对象会包装到数组中。可以像这样修复
get '/api/users/:fb_id' do |fb_id|
user = User.find_by_fb_id(fb_id)
user.to_json :methods => :new_cookies
end
关于ruby-on-rails - to_json 将单个对象包装在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13599462/