ruby-on-rails - rails 3.2 : Replace null values with empty string from json serialization

标签 ruby-on-rails ruby json serialization ruby-on-rails-3.2

我正在使用 Rails 3.2 serialization将 ruby​​ 对象转换为 json。

例如,我已经将 ruby​​ 对象序列化为以下 json

{
  "relationship":{
    "type":"relationship",
    "id":null,
    "followed_id": null
  }
}

在我的类 Relationship < ActiveRecord::Base 中使用以下序列化方法

def as_json(opts = {})
  {
   :type        => 'relationship',
   :id          => id,
   :followed_id => followed_id
  }
end

我需要用空字符串替换空值,即空双引号,以响应 json。

我怎样才能做到这一点?

最好的问候,

最佳答案

我没有看到这里的问题。只需通过 || 运算符即可:

def as_json(opts = {})
  {
   :type        => 'relationship',
   :id          => id || '',
   :followed_id => followed_id || ''
  }
end

关于ruby-on-rails - rails 3.2 : Replace null values with empty string from json serialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811628/

相关文章:

php - 使用 Laravel 在 Json 列中搜索

ruby-on-rails - rails : build array with the value from a certain model attribute

ruby-on-rails - 使用 Fog AWS S3 和 Rails 时出现负过期

ruby-on-rails - RSpec Controller 测试将哈希转换为字符串

javascript - Eval 不起作用 - JavaScript

sql - 如何在SQL中使用group by生成json数据

ruby-on-rails - rvm 安装 : ruby installation error

ruby-on-rails - 如何使用 Nokogiri 和 at_css 获取 img src

ruby - 错误 : disable image loading on watir with firefox

ruby - 在本地安装 gem 命令