Search code examples
ruby-on-railsvalidationruby-on-rails-4

rails 4 before_validation on: :create or on: :save


I am having a case which is getting around my head.

I have an Image model which I only want to save if it gets uploaded. I also need some information coming from the upload to validate the image(like height and width). But I want only the upload to happen if somebody is trying to save the file the image for the first time.

So I thought the best option would be to have a before_validation, but I would like it to run only on save!

My code is on this gist https://gist.github.com/andreorvalho/b21204977d2b70fdef83

So the weird part is this on: :save and on: :create have really weird behaviours or at least not what I expected.

When I put it as on: :save If I try to do an image.save on a test I can see my before_validation callbacks are not ran!

If I put on: :create is ran in every situation is does not matter if I ran image.save, image.create or image.valid?

So I am guessing this is either not working or I am misunderstanding the goal of those on settings.

p.s. my validation on create, also occurs in every situation save, create or valid?

let me know if anybody ran into the same or knows why is not supposed to work like this.


Solution

  • The before_validation callback allows restrictions to particular events within the lifecycle of an object.

    You can use the following syntax:

    before_validation :set_uuid, on: :create
    before_validation :upload_to_system, on: [:create, :update]
    

    Here is the documentation of this option for Rails 4.0, Rails 5.2, Rails 6.0 and Rails 7.0.