这是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的照片,这不应该发生。
请向我解释我做错了什么?
答案 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