为什么自定义验证在RoR 3中不起作用

时间:2012-09-15 12:30:46

标签: ruby-on-rails ruby-on-rails-3 validation activerecord

这是Photo模型类的代码:

class Photo < ActiveRecord::Base

  belongs_to :user
  belongs_to :organization

  validate :user_id_or_organization_id_cant_be_blank

...

  def user_id_or_organization_id_cant_be_blank
      if !:user_id? and !:organization_id?
        errors.add(:user_id, "no user")
        errors.add(:organisation_id, "no organization")
      end
  end

问题在于验证。它不起作用,我不明白为什么。

我可以创建一张没有user_id或organization_id的照片,这不应该发生。

请向我解释我做错了什么?

2 个答案:

答案 0 :(得分:1)

你宁愿这样做:

def user_id_or_organization_id_cant_be_blank
  if user_id.blank? && organization_id.blank?
    errors.add(:user_id, "no user")
    errors.add(:organisation_id, "no organization")
  end
end

答案 1 :(得分:1)

Rails提供了检查存在的标准方法:

validates :user_id, :organization_id,  presence:   true

如果您需要进行复杂验证,请尝试使用 ActiveModel :: Validator

class Photo < ActiveRecord::Base
  validates_with UserOrganizationIdsValidator
end

class UserOrganizationIdsValidator < ActiveModel::Validator
  def validate(record)
    if user_id.blank? && organisation_id.blank?
       errors.add(:user_id, "no user")
       errors.add(:organisation_id, "no organization")
    end
    # something custom else...
  end
end