【问题标题】:rails 3 ruby 2 conditional validations not working as expectedrails 3 ruby​​ 2 条件验证未按预期工作
【发布时间】:2013-08-04 17:52:46
【问题描述】:

我只想在 user_id 字段为空时验证 note 字段?

我尝试不使用 lambda:

   validates_presence_of :note, :unless => user_id?

我尝试了一个方法:

   validates_presence_of :note, :unless => user_is_present?
   def user_is_present?
      self.user_id.present?
   end

我尝试了一个 lambda:

  validates_presence_of :note, :unless => lambda { self.user_id.present? }

我尝试了一个 Proc

  validates_presence_of :note, :unless => Proc.new { |x| x.user_id.present? }

所有结果:

  "Called id for nil, which would mistakenly be 8 -- if you really wanted the id of nil, use object_id"

Trial & Error 确认 nil 值是 user_id...未验证且不应该失败。

  1. 第一个问题是我的尝试是否有任何错误?
  2. 第二个问题是我怎样才能做到这一点?

【问题讨论】:

    标签: ruby-on-rails-3 validation conditional ruby-2.0


    【解决方案1】:

    我会试试的

    validates :note, presence: true, unless: 'user_id'
    

    您不需要定义任何方法...

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 2014-01-07
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多