Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 : Do i need to give return true in a before_save callback for an object.save to work?

Tags:

Class User     before_save :set_searchable    def set_searchable       self.searchable = true if self.status == :active     end   end    >> u = User.last   >> u.save   false   

u.save always return false. If i remove the before_save it works also if i give a return true in before_save it works

so do i need to give return statements in before_save ? will ActiveRecord saves an object if the before_save returns false ?

Where can i see a full documentation regarding callbacks and its workflow .

Thanks in advance

like image 230
Krishna Prasad Varma Avatar asked Jan 19 '11 12:01

Krishna Prasad Varma


People also ask

How does Callback work in Rails?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is around callback in rails?

In Rails, callbacks are hooks provided by Active Record that allow methods to run before or after a create, update, or destroy action occurs to an object. Since it can be hard to remember all of them and what they do, here is a quick reference for all current Rails 5 Active Record callbacks.

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

From: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

So, yes.

like image 78
noodl Avatar answered Feb 04 '23 23:02

noodl