mysql - Rails & JBuilder - DECIMAL(10,2) 输出为字符串的数据类型

标签 mysql ruby-on-rails json

我在使用继承的 Rails 应用程序时遇到问题,而且我没有 Rails 经验。它使用 JBuilder 从 MySQL 数据库返回 JSON 响应。我更新了应用程序,向数据库添加了几个新列,类型为 DECIMAL(10,2) 。问题是,当我请求 JSON 时,该值以字符串形式返回。如果我使用 DECIMAL(10,0)然后它作为数字返回。有没有办法强制 JBuilder 返回一个数字?相关参数为以下示例中的game_score。

Controller 的相关部分:

  # GET /game
  # GET /game.json
  def index
    if params[:since]
      since_datetime = Time.parse(params[:since])
      @game = current_user.game.where(["updated_at >= ? and deleted is not true",  since_datetime])
    else
      @game = current_user.game.where('deleted is not true')
    end

  end

index.json.jbuilder 文件:

json.array!(@game) do |game|
   json.extract! game, :id, :game_date, :game_score, :game_location, :game_team, :game_referee
   json.url game_url(game, format: :json)
end

当 MySQL 数据类型为 DECIMAL(10,2) 时为 JSON :

[{"id":4814,"game_date":"2014-09-10T15:51:00.000Z","game_score":"1.55","game_location":null,"game_team":"Team 1","game_referee":null, "url":"http://[ip]/game/4814.json"}]

当 MySQL 数据类型为 DECIMAL(10,0) 时为 JSON :

[{"id":4814,"game_date":"2014-09-10T15:51:00.000Z","game_score":1,"game_location":null,"game_team":"Team 1","game_referee":null, "url":"http://[ip]/game/4814.json"}]

最佳答案

最简单的方法是手动编写此字段,例如:

json.game_score game.game_score.to_f

关于mysql - Rails & JBuilder - DECIMAL(10,2) 输出为字符串的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25621470/

相关文章:

ios - 请求 addValue : forHTTPHeaderField gets the token but does not sends it to server in RestKit

android - 仅使用 Jackson 将父类(super class)字段序列化为 JSON

php - 执行多个查询然后输出为数组

php - 使用 Ajax 和 mySQL 进行 jQuery 排序

mysql - 如何检索所有未回答的问题)?

ruby-on-rails - Ruby on Rails Rack Cors 中间件黑名单

ruby-on-rails - 长度验证测试 Rails 测试 :Unit

javascript - 在 Node.js 应用程序和 Rails 应用程序之间共享 session

python - 将 Pandas Dataframe 转换为自定义嵌套 JSON

php - Yii2 迁移事务方法,safeup() 和 safedown() 不起作用