Rails: How do I cancel a save if the before_update callback returns false?

I have a model that has a callback before_update. From my understanding before_update, it update_attributesis called when called in the model instance. My assumption is that if the callback before_updatereturns false, the record will not be updated.

This does not seem to work as intended. Every time I call update_attributes, the record is saved, even if it before_updatereturns false. You do not know how to prevent record updating if before_updatereturns false? Here is what I tried in the user.rb file:

class User < ActiveRecord::Base

  validates :first_name, :last_name,  :presence => true

  before_update do
    false
  end

end

Here is what I tried in the rails console:

u = User.new(:first_name=>"John", :last_name => "Doe")
=> #<User id: nil, first_name: "John", last_name: "Doe", created_at: nil, updated_at: nil> 

u.update_attributes(:first_name=>nil)
=> false 

u.changed?
=> true 

u
=> #<User id: nil, first_name: nil, last_name: "Doe", created_at: nil, updated_at: nil> 
+3
source share
1 answer

Ruby. , - ​​ .

Rails , .

+6

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


All Articles