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.
create! creates the object and tries to save it but raises an exception if validations fails, e.g. . new and . save!
9 Callback Classes You can declare as many callbacks as you want inside your callback classes.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With