Rails 3.2 Preventing Object Saving with Errors

I have an ActiveRecord object, and I would like to prevent it from being saved, without constantly checking the model. You used to be able to do something like this with errors.add , but it looks like it no longer works.

 user = User.last user.errors.add :name, "name doesn't rhyme with orange" user.valid? # => true user.save # => true 

or

 user = User.last user.errors.add :base, "my unique error" user.valid? # => true user.save # => true 

How can I prevent a user object from being saved in Rails 3.2 without modifying it?

+4
source share
3 answers

You can set errors , but do so as part of a validation method, for example:

 validate :must_rhyme_with_orange def must_rhyme_with_orange unless rhymes_with_orange? errors.add(:name, "doesn't rhyme with orange") end end 

If you want to conditionally run a check, one trick is to use attr_accessor and the protection state:

 attr_accessor :needs_rhyming validate :must_rhyme_with_orange, :if => Proc.new {|o| o.needs_rhyming} > u = User.last > u.needs_rhyming = true > u.valid? # false 
+7
source

Does your problem work? will restart the checks .. reset your errors.

  pry(main)> u.errors[:base] << "This is some custom error message" => ["This is some custom error message"] pry(main)> u.errors => {:base=>["This is some custom error message"]} pry(main)> u.valid? => true pry(main)> u.errors => {} pry(main)> 

Instead, just check if there are u.errors.blank?

+2
source

This is a slight deviation from the original question, but I found this post after several attempts. Rails has built-in functionality to reject an object from being saved if it has the _destroy attribute set to true. Very useful if you control the creation of a model at the controller level.

0
source

Source: https://habr.com/ru/post/1401057/


All Articles