Ruby Sequel model to have validation for create and not update
Asked Answered
V

3

5

How I can I avoid having validation for update while having it for create? For instance:

I wish to have an image field to have presence validation on create. But want to avoid it in edit and assume the previous value in case of no change.

Note: I am using Padrino.

Valedictorian answered 16/10, 2014 at 7:16 Comment(0)
K
10

In Sequel, validations are generally done at the instance level using the validation_helpers plugin. So you just use a standard ruby conditional if you only want to validate it for new objects and not for existing ones:

plugin :validation_helpers
def validate
  super
  validates_presence :image if new?
end
Keane answered 16/10, 2014 at 17:47 Comment(1)
Wow, didn't know that new? existed! Anyways great its a great ORM, thanks for it!Valedictorian
H
0

you can say something like:

validates :image, :presence => true, on: :create

that means you will do validation only when do create.

Hexose answered 16/10, 2014 at 10:7 Comment(0)
U
0

In Rails,

The "validates" keyword in Rails takes a parameter that allows you to do this:

validates :your_validator, :presence => true, :on => :create

You can also pass an array there:

validates :your_validator, :presence => true, :on => [:create, :update]

In Padrino,

I believe padrino using datamapper - DM has contextual validations. So, you could do a contextual validation.

validates :image, :presence => true, :when => [:custom]

Then while saving, you can do this:

post.save(:custom)
# OR
post.valid?(:custom)

The context :custom can be used in different places.

Unpleasantness answered 16/10, 2014 at 10:15 Comment(3)
I think thats a Rails specific helper. I am using Padrino, my bad I should probably have mentioned.Valedictorian
I didn't expect it to be a Padrino model :) I have updated my answer. I believe Padrino uses datamapper.Unpleasantness
No, Padrino is ORM agnostic and I am using Sequel. Thanks for answering anyway.Valedictorian

© 2022 - 2024 — McMap. All rights reserved.