Reputation: 561
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?
Upvotes: 0
Views: 286
Reputation: 15530
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
Upvotes: 1
Reputation: 115531
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
Upvotes: 1