Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 447
andre.orvalho Avatar asked Jan 27 '14 22:01

andre.orvalho


People also ask

Does Rails create save?

create! creates the object and tries to save it but raises an exception if validations fails, e.g. . new and . save!

How many callbacks are there in Rails?

9 Callback Classes You can declare as many callbacks as you want inside your callback classes.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

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.

like image 90
Jon Avatar answered Sep 30 '22 08:09

Jon