2017-07-25 97 views
0

我刚刚遇到Validate presence of field only if another field is blank - Rails的接受解决方案未完成的情况。验证两个字段中的一个字段是否为零

我想的一个或两个两个字段的是存在的,但在我的情况points需要是0和10之间的数。在情况下点字段是零:points?字段中的一个被评估为假,并空白的评论被认为是无效的。我试图使它成为一个更具体一点通过指定:points.blank?

validates :comment, presence: { unless: :points.blank?, on: :create } 
validates :points, presence: { unless: :comment?, on: :create }, 
        numericality: { only_integer: true, allow_nil: true, less_than_or_equal_to: 10, greater_than_or_equal_to: 0 } 

,似乎工作(我可以保存0分,没有注释的第一项),但在随后的节省我越来越从奇怪的错误控制器:

NoMethodError(未定义的方法 '验证' 假:FalseClass): 应用程序/控制器/ comments_controller.rb:8:在 '创建'

别的东西在那里我需要做的w ^是否验证?我是否需要使用lambda(正如链接问题的一些答案中所建议的)?

回答

0

不知道你是如何得到第一个记录的工作,但是这是不正确的语法:

验证:评论,存在:{除非:points.blank?上:创建}

相反,你应该定义这样的方法在你的模型:

def points_blank? 
    # your code for zero handling 
    # 
end 

,然后使用该方法,除非这样的:

validates :comment, presence: { unless: :points_blank?, on: :create } 
+0

结束了去:'验证:has_comment_or_points上:create',做所有的逻辑在方法 –

2

:points.blank?的计算结果为false,它被设置为散列中:unless键的值。您需要指定方法名称或Proc才能使:unless选项生效。您可以简化整个设置:

validates :comment, presence: true, on: :create, if: :points? 
validates :points, numericality: :only_integer, inclusion: 0..10 
+0

感谢@coreyward但(使用'除非:点? '而不是'如果......:点?')把我带回我最初的问题。如果我给某人零分,我不能给他们一个空白的评论。验证失败是因为':points => 0'时':points?'的计算结果为false。 –

+0

@MatthewLindfieldSeager然后你可以创建你自己的方法。 'def points_present?; points.present ?; end' – coreyward

相关问题