新手问题 Rails 中遇到 Integer 类型的变量在嵌套 hash 中显示为 “#” 的问题

killernova · September 06, 2015 · Last by hiveer replied at September 07, 2015 · 1944 hits

首先定义了一个变量:

@cart_total = @line_items.select{|x| x.product.present? }.collect{ |x| (x.product.price*x.quantity) }.inject(:+) || 0

在 controller 中有如下语句:

final_amount = @cart_total
params[:order].merge!(:final_amount => final_amount)
return render :text => "#{params[:order][:final_amount]} => #{params[:order]}"

该页面的显示结果为:

38.0 => {"shipping_id"=>"1", "ship_day"=>"任意日期", "ship_special"=>"", "ship_time2"=>"任意时间段", "part_pay"=>"4", "payment"=>"wxpay", "memo"=>"", "is_tax"=>"false", "tax_company"=>"",  "ship_zip"=>"", "ship_tel"=>"", "ip"=>"127.0.0.1", "member_id"=>4451, "supplier_id"=>1, "status"=>"active", "final_amount"=>#}

也就是说,params[:order][:final_amount] = 38.0, 而params[:order]中的最后一项值为::final_amount => #

但若是把final_amount = @cart_total 改为final_amount = @cart_total.to_i, 那么一切都正常,params[:order]中的最后一项值为::final_amount => 38.0

另外,@cart_amount.kind_of(Integer)的结果是 true.

请问为什么会出现这种情况?@cart_total的值为什么需要 to_i 后才能在params[:order]中正常显示?为什么params[:order][final_amount]就可以直接显示?

跟对象序列化有关吧,可能是将数字序列化错了。

因为是 BigDecimal 吧,为何这么确定是 integer?

@nouse 呃,我不是很懂,只是因为 kind_of?(Integer) 返回 true。如果是 BigDecimal,请问该问题是由于这个原因引起的吗?

没实际环境不好说。通过以下的方式去调试吧:

  • 检查final_amount.class
  • 试着用final_amount.to_f
  • 试着稍微更改以下params[:order]['final_amount']的值,使他和final_amount不一样。

不晓得你用的 rails 版本是什么,我这里自己 demo 了一下,没有什么问题

def index
  @cart_total = "38.0"
  final_amount = @cart_total
  params[:order] = {"shipping_id"=>"1",
                    "ship_day"=>"任意日期",
                    "ship_special"=>"",
                    "ship_time2"=>"任意时间段",
                    "part_pay"=>"4",
                    "payment"=>"wxpay",
                    "memo"=>"",
                    "is_tax"=>"false",
                    "tax_company"=>"",
                    "ship_zip"=>"",
                    "ship_tel"=>"",
                    "ip"=>"127.0.0.1",
                    "member_id"=>4451,
                    "supplier_id"=>1,
                    "status"=>"active"}.with_indifferent_access
  params[:order].merge!(:final_amount => final_amount)
  return render :text => "#{params[:order][:final_amount]} => #{params[:order]}"

You need to Sign in before reply, if you don't have an account, please Sign up first.