Rails中使用类方法实现sort_by排序遇类型错误求助
问题分析与解决
错误TypeError: String can't be coerced into Integer触发在加法操作中,说明执行points += X时,X的运算结果是字符串类型,而初始值为整数的points无法与字符串直接相加。
你单独调用类方法时正常,但sort_by会遍历all_datsk_hpe中的所有实例,这意味着集合中至少有一个实例的属性值不符合预期(是未转换的字符串类型)。
问题定位
代码中有两处关键隐患:
hpe.gen_acd:仅对hpe.gen_aa/hpe.gen_amc做了to_i转换,但gen_acd如果是字符串(比如"3"而非整数3),乘法结果会是字符串,与整数points相加就会报错。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
相关产品推荐
相关产品推荐

