Jam*_*mes 11 validation activerecord ruby-on-rails ruby-on-rails-3 rails-activerecord
我正在尝试创建一个条件,其中属性'one'为零,属性'two'为1,则模型无效.但是当我做:
Model.create(:one => 1, :two => 0).valid?
Run Code Online (Sandbox Code Playgroud)
单元测试返回true!为什么?
validates :one, :two, :presence => true, :if => :if condition_testing?
def condition_testing?
!(one == 0 && two == 1)
end
Run Code Online (Sandbox Code Playgroud)
Tig*_*ine 18
我认为你的语法有错误:
validates :one, :two, :presence => true, :if => :condition_testing?
def condition_testing?
!(one == 0 && two == 1)
end
Run Code Online (Sandbox Code Playgroud)
有一个:如果那里有太多......如果我理解正确你想要它只是验证以防万一one == 0 && two == 1?那你条件测试?倒置(省略!())
如果不确定你可以尝试使用pry并在condition_testing?方法中插入一个断点来查看正在发生的事情.
(请注意在条件测试前添加":")
pot*_*hin 11
您可以在一行中验证它:
validates :one, :two, :presence => true, :if => Proc.new { |a| !(a.one == 0 && a.two == 1) }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42062 次 |
| 最近记录: |