Rails 3 -在Exception中对虚拟属性结果进行验证



在我的一个模型中有一个名为currentBalance的虚拟属性。我的视图中的ajax调用填充这个属性。在模型中,我试图验证net_weight小于或等于currentBalance,它表示库存中产品的总净重。

问题似乎是net_weight是一个浮点数,currentBalance属性作为一个字符串返回,导致一个异常,说:

Float与String的比较失败

当一个产品被选中时,这里是填充currentBalance输入字段的jquery:

$( ".fields" ).each( function(){    
    <% @currentBals.each do |c| %>
        if( $(this).find("option:selected").text() == '<%= c.material %>' ) {   
            $(this).find("input:text[readonly]").val("<%= number_with_delimiter(c.currentBal) %>")  
        } else {
            if ($(this).find("option:selected").text() == 'Select Material'){
                $(this).find("input:text[readonly]").val("<%=  number_with_delimiter(0) %>")
            }
        }
    <% end %>    
});

,下面是模型中的验证代码:

validates :net_weight, presence: true, numericality: { greater_than: 0.0, less_than_or_equal_to: :currentBalance }

我认为是number_with_delimiter格式语句导致了这个问题。但我希望值在视图中被格式化。

我怎么能改变验证或转换currentBalance属性是一个浮点之前验证运行?

当前余额的输入标签类型为text。试着把这个标签改成

number(type="number")),对于浮点数,增加一个step属性(e)。g step="0.01"),改变

$(this).find("input:text[readonly]") 

$(this).find("input:number[readonly]")

所以我找到了一个解决方案,虽然我认为这有点黑客。在控制器的create操作中,我循环遍历每个细节记录,并从currentBalance属性中解析出逗号,然后对其调用.to_f。

@shipment.details.each do |d|
         d.currentBalance = d.currentBalance.delete(',').to_f
end

我更愿意把这个逻辑推到模型中,但是在多次尝试之后(为了节省时间),这个方法起作用了。如果有人知道如何将逻辑推入细节模型并确保其正确验证,我很乐意尝试。

最新更新