【问题标题】:to_json wrapping a single object in array?to_json 将单个对象包装在数组中?
【发布时间】:2012-11-15 23:21:04
【问题描述】:

在我的 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, ....}]

我该如何解决这个问题,更重要的是,为什么?!?

【问题讨论】:

  • 您是如何获得user.to_json :methods => :new_messages 中的user 的?

标签: ruby-on-rails activerecord sinatra


【解决方案1】:

只需使用Hash.[]

 Hash[{a: :b}]
 # => {:a=>:b}

更重要的是,为什么?!?

您在第二个示例中使用的是哪个 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

【讨论】:

  • OP 在第二个示例中指的是 Sinatra,AFAIK 没有 ActiveRecord::Relation
  • 是的,你是对的。 Sinatra 本身没有 ORM。我假设 OP 使用 ActiveRecord,因为它最受欢迎。
【解决方案2】:

替换这一行:

user = User.where :fb_id => fb_id

用这一行:

user = User.find_by_fb_id fb_id

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2014-09-02
    相关资源
    最近更新 更多