I have previously written a post about Find or create by and its usages in Rails 3 but Rails have gotten several version updated since then and some of the things I mentioned have even been deprecated at this time, so I wanted to revisit this very useful method again.
Scoping in Ruby on Rails allows us to define frequently used queries which can be invoked as method calls on either association objects, relations or models. You can reference the standard query methods like
includes. The requirements of defined scopes is that it must return either an instance of
nil. This allows us to chain multiple scopes together for highly flexible query construction.
ActiveRecord has a lot of callbacks but probably one of the most frequently used ones is
before_save. There are a few other ones that are very similar like
before_update, but they are just more narrowly scoped callbacks hat otherwise does the same thing.
When writing controllers in Ruby on rails, using
before_action (used to be called
before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It’s what you want to use to “prepare” the data necessary before the action executes.