calling custom validation methods in Rails

前端 未结 3 1908
离开以前
离开以前 2021-01-30 06:42

I just upgraded my rails to 2.3.4 and I noticed this with validations: Lets say I have a simple model Company which has a name. nothing to it. I want to run my own validation:<

3条回答
  •  情书的邮戳
    2021-01-30 06:55

    Your validations are executed when you use the validate method. However rails doesn't relies on the returned value.

    It relies on if there are validations errors or not. So you should add errors when your model doesn't validates.

    def something
        errors.add(:field, 'error message')
    end
    

    Or, if the error is not related to a field :

    def something
        errors.add(:base, 'error message')
    end
    

    Then your model won't be saved because there are errors.

提交回复
热议问题