简体   繁体   中英

Why doesn't custom validation work in RoR 3

Here is my code for the Photo model class:

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

The problem is in the validation. It doesn't work, and i don't understand why.

I can create a photo with no user_id or organization_id which is not supposed to happen.

Please explain to me what i'm doing wrong?

You'd rather do:

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

Rails provides the standard approach to check the presence:

validates :user_id, :organization_id,  presence:   true

If you need to do a complex validation, try to use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM