我认为你做得对。此测试通过:
test "should remove commas from thenumber" do
f = Foo.new(:thenumber => "10,000")
f.save
f = Foo.find(f.id)
assert f.thenumber == "10000"
end
我用你的代码。现在
class Foo < ActiveRecord::Base
before_validation :normalize
def normalize
self['thenumber'] = self['thenumber'].to_s.gsub(',','')
end
end
,我的架构设立数量写是一个字符串,虽然,不是一个整数。
Started
.
Finished in 0.049666 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
如果你想这些信息存储在数据库作为一个整数,那么你一定需要重写二传手:
def thenumber=(value)
self['thenumber'] = value.to_s.gsub(',','').to_i
end
如果你做你的方式,用一个整数列,它会通过AR截断....
>> f.thenumber = "10,000"
=> "10,000"
>> f.thenumber
=> 10
这是一个鲜为人知的事情用Ruby和整数...它自动铸件通过截取任何不再是一个整数。
irb(main):004:0> i = "155-brian-hogan".to_i
=> 155
可以是很酷的东西像
/users/155-brian-hogan
@user = User.find_by_id(params[:id])
但不是很爽为你在做什么。
山坳所以要么改变为字符串,并使用过滤器,或改变二传手:)
祝你好运!
是的,我已经辞去了自己在控制器中正常化参数,然后他们完全进入AR ... – Bill 2009-05-19 18:40:58