Ruby on rails 如何将的validates\u numericality\u更改为validate on rails
我如何改变Ruby on rails 如何将的validates\u numericality\u更改为validate on rails,ruby-on-rails,validation,model,Ruby On Rails,Validation,Model,我如何改变 validates_numericality_of :test, :greater_than_or_equal_to=>0 变成有效形式 我只尝试了字符和零值。我还需要检查它必须大于0 validate change_test def change_test if @test.nil? errors.add_to_base('Hi Test should be only number') end end 我也试着这样做 validate change_
validates_numericality_of :test, :greater_than_or_equal_to=>0
变成有效形式
我只尝试了字符和零值。我还需要检查它必须大于0
validate change_test
def change_test
if @test.nil?
errors.add_to_base('Hi Test should be only number')
end
end
我也试着这样做
validate change_test
def change_test
if @test.nil?
errors.add_to_base('Hi Test should be only number')
else
if @test < 0
errors.add_to_base('The number should be greater than or equal to 0')
end
end
end
验证更改\u测试
def更换测试
如果@test.nil?
错误。将_添加到_基('Hi测试应仅为数字')
其他的
如果@test<0
错误。将_添加到_基('数字应大于或等于0')
结束
结束
结束
但这是错误的结果
请帮忙解决这个问题
谢谢大家
:message
参数为验证
的数值性)if@test<0
应该是if@test.to_i
<0:message
参数为验证
的数值性)if@test<0
应该是if@test.to_i
<0您的代码需要更改为:
validate :change_test
def change_test
if test.nil?
errors.add_to_base('Hi Test should be only number')
end
end
您的代码有两个问题:
1.验证方法需要使用符号作为参数。
2.我假设test是属性,您不应该使用@symbol 因此,对于代码的最后一部分,应该是:
class Money < ActiveRecord::Base
validate :change_test
# We are validating an attribute of the Money model called test
def change_test
# This is to test for nil value which is empty string
if test.blank?
errors.add_to_base('Hi Test value cannot be empty')
end
# This is to make sure value is greater than or equal to 0
if test.to_i < 0
errors.add_to_base('The number should be greater than or equal to 0')
end
end
end
class Money
请注意,测试不是对象。它是模型类中的一个属性
我希望这有帮助。您的代码需要更改为:
validate :change_test
def change_test
if test.nil?
errors.add_to_base('Hi Test should be only number')
end
end
您的代码有两个问题:
1.验证方法需要使用符号作为参数。
2.我假设test是属性,您不应该使用@symbol 因此,对于代码的最后一部分,应该是:
class Money < ActiveRecord::Base
validate :change_test
# We are validating an attribute of the Money model called test
def change_test
# This is to test for nil value which is empty string
if test.blank?
errors.add_to_base('Hi Test value cannot be empty')
end
# This is to make sure value is greater than or equal to 0
if test.to_i < 0
errors.add_to_base('The number should be greater than or equal to 0')
end
end
end
class Money
请注意,测试不是对象。它是模型类中的一个属性
我希望这会有所帮助。如果我使用内置验证,错误消息examples test:附带的字段名无效我不想显示test:所以我转向了用户定义的validatean,并且错误是未定义的方法“to_i”for#;看起来您是在对Money对象调用_i,而不是对Money对象的test属性调用。希望这有帮助。如果我使用内置验证,错误消息examples test:附带的字段名无效我不想显示test:所以我转向了用户定义的validatean,并且错误是未定义的方法“to_i”for#;看起来您是在对Money对象调用_i,而不是对Money对象的test属性调用。希望这有帮助。问题仍然出现,局部变量和实例变量在这里的作用相同问题仍然出现,局部变量和实例变量在这里的作用相同