【问题标题】:Rails & JBuilder - Data type of DECIMAL(10,2) output as a stringRails & JBuilder - DECIMAL(10,2) 的数据类型输出为字符串
【发布时间】:2014-09-02 10:42:11
【问题描述】:

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

控制器的相关部分:

  # 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"}]

【问题讨论】:

    标签: mysql ruby-on-rails json


    【解决方案1】:

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

    json.game_score game.game_score.to_f
    

    【讨论】:

      猜你喜欢
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      相关资源
      最近更新 更多