You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails中使用类方法实现sort_by排序遇类型错误求助

问题分析与解决

错误TypeError: String can't be coerced into Integer触发在加法操作中,说明执行points += X时,X的运算结果是字符串类型,而初始值为整数的points无法与字符串直接相加。

你单独调用类方法时正常,但sort_by会遍历all_datsk_hpe中的所有实例,这意味着集合中至少有一个实例的属性值不符合预期(是未转换的字符串类型)。

问题定位

代码中有两处关键隐患:

  1. hpe.gen_acd:仅对hpe.gen_aa/hpe.gen_amc做了to_i转换,但gen_acd如果是字符串(比如"3"而非整数3),乘法结果会是字符串,与整数points相加就会报错。
  2. hpe["ad_c_#{num}_discount"]:该属性未做to_i转换,若值为字符串,乘法后得到的字符串无法和整数points相加。

修复方案

给所有参与乘法运算的属性添加to_i转换,确保运算结果为整数类型:

def self.datsk_point_count(hpe)
    points = 0
    if hpe.gen_ac != ""
      if hpe.gen_aa != nil
        # 给gen_acd添加to_i转换
        points += hpe.gen_aa.to_i * hpe.gen_acd.to_i
      else
        points += hpe.gen_amc.to_i * hpe.gen_acd.to_i
      end
    else
      (1..10).each do |num|
        if hpe["ad_c_#{num}"] != ""
          # 提前将discount转为整数
          discount = hpe["ad_c_#{num}_discount"].to_i
          if hpe["ad_c_#{num}_available"] != nil
            points += hpe["ad_c_#{num}_available"].to_i * discount
          else
            points += hpe["ad_c_#{num}_max_capacity"].to_i * discount
          end
        end
      end
    end
    points
end

额外建议

  • 在模型层给相关属性设置默认值(比如default: 0),避免空值或非数值类型的输入。
  • 提前排查all_datsk_hpe集合中的实例,定位哪些实例的gen_acd或ad_c_*_discount是字符串类型,从根源上统一数据类型。

内容的提问来源于stack exchange,提问作者daveasdf_2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:45:03