加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:验证foo的存在,除非bar ==’baz’

发布时间:2020-12-17 04:18:10 所属栏目:百科 来源:网络整理
导读:我正在研究一个模型,该模型在创建对象时需要设置两个关联,在一种情况下除外. 基本上,它需要像这样工作. class Example ActiveRecord::Base has_one :foo has_one :bar validates_presence_of :foo validates_presence_of :bar,:unless = :foo == Foo.find_by
我正在研究一个模型,该模型在创建对象时需要设置两个关联,在一种情况下除外.

基本上,它需要像这样工作.

class Example < ActiveRecord::Base
  has_one :foo
  has_one :bar

  validates_presence_of :foo
  validates_presence_of :bar,:unless => :foo == Foo.find_by_name('ThisFooDoesntLikeBars')
end

我不确定如何构建:除非条件在这里,因为它需要检查:foo是否是特定对象.

你怎么做这样的事情?

解决方法

:除非接受Proc
validates_presence_of :bar,:unless => Proc.new { |ex| ex.foo == Foo.find_by_name('ThisFooDoesntLikeBars') }

:unless – Specifies a method,proc or string to call to determine if the validation should not occur (e.g. :unless => :skip_validation,or :unless => Proc.new { |user| user.signup_step <= 2 }). The method,proc or string should return or evaluate to a true or false value.

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读