首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails & JBuilder -作为字符串输出的十进制(10,2)数据类型

Rails & JBuilder -作为字符串输出的十进制(10,2)数据类型
EN

Stack Overflow用户
提问于 2014-09-02 10:42:11
回答 1查看 1.4K关注 0票数 2

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

主计长的有关部分:

代码语言:javascript
复制
  # 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文件:

代码语言:javascript
复制
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

代码语言:javascript
复制
[{"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

代码语言:javascript
复制
[{"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"}]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-02 10:49:53

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

代码语言:javascript
复制
json.game_score game.game_score.to_f
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25621470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档