rails 3 ruby​​ 2条件验证未按预期工作

时间:2013-08-04 17:52:47

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

我想仅在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"

试用&错误确认是nil值是user_id ...未经验证且不应失败。

  1. 第一个问题是我的尝试有错误吗?
  2. 第二个问题是我该如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我会尝试

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

您无需定义任何方法......