Rails - 如何仅在另一个字段具有特定值时验证字段? [英] Rails - How to validate a field only if a another field has a certain value?

查看:18
本文介绍了Rails - 如何仅在另一个字段具有特定值时验证字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Rails 还很陌生,现在遇到了一个问题,我的朋友 Google 无法解决这个问题:)

I'm pretty new to Rails and I now came across a problem which I wasn't able to solve with my friend Google :)

在我的表单中,我有一个包含三个值的 Select:AppleBananaCherry.如果我选择苹果,我隐藏了一个带有一些javascript的另一个选择 - 和一个文本字段,因为选择苹果时,无需填写这些其他两个字段了.

In my form I have a Select with three values: Apple, Banana and Cherry. If I choose Apple from the select I hide another Select- and a Text-field with some Javascript, because when Apple is chosen, there is no need to fill in these other two fields anymore.

所以现在我在提交表单时验证表单有问题.我发现了一些类似的问题,例如只有在另一个字段为空时才验证一个字段."

So now I have a problem with validating my form when it's submitted. I've found some similar problems for example in the case of "Only validate a field if another is blank."

这个问题是这样解决的:

This Problem was solved like this:

validates_presence_of :mobile_number, :unless => :home_phone?

所以我刚刚尝试了我想到的第一件事:

So I've just tried the first thing which popped into my mind:

validates_presence_of :state, :granted_at, :if => :type != 1

但是当我运行它时,我得到这个错误:

But when I run it, I get this error:

undefined method `validate' for true:TrueClass

所以现在我没有找到如何从创建的对象中访问值...提前感谢您的帮助,我希望我的问题不像听起来那么明显:-)

So now I didn't find out how I can access values from the object which was created... Thank you in Advance for your help and I hope my question isn't as obvious as it sounds :-)

推荐答案

因为它是可执行代码,所以您需要将其包装在 lambda 或 Proc 对象中,如下所示:

Because it is executable code you need to wrap it in a lambda or a Proc object like so:

validates_presence_of :state, :granted_at, :if => lambda { |o| o.type != 1 }

# alternatively:
..., :if => lambda { self.type != 1 }
..., :if => Proc.new { |o| o.type != 1 }
..., :if ->(o) { o.type != 1 }

这篇关于Rails - 如何仅在另一个字段具有特定值时验证字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆