Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do ActiveRecord callbacks require instance variables or instance methods to be prefixed with self keyword?

Tags:

ActiveRecord has a few different callback methods used to simplify model logic. For example after_find and before_create methods.

Consider this code example:

class ExternalPrintingCard < ActiveRecord::Base   belongs_to :user   belongs_to :ph_user    after_create :change_pin    def change_pin     self.user.randomize_printer_pin   end    def after_find     return if self.card_status == false     self.card_status = false if self.is_used_up?     self.card_status = false if self.is_expired?     self.save!   end end 

If I remove all the self prefixes from the instance variables or instance methods, these 2 callbacks will be called, but it is as if they are local variables inside these callback methods.

This instance variable (card_status), instance methods (save!, is_used_up? and is_expired?) and association (user) worked fine outside these 2 callback methods without the self prefix.

The sample code in the Rails' documentation for callback methods (instance methods), seems to always use the self prefix even though it is calling instance variables or methods, which by right they are accessible without the self prefix normally.

I hope someone with a better understanding of ActiveRecord callbacks can help to shed a light on this behaviour.

Cheers

like image 554
Samuel Chandra Avatar asked Sep 30 '09 06:09

Samuel Chandra


People also ask

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is callbacks in Ruby on 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 controller callback in rails?

During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks (called callbacks) into this object life cycle so that you can control your application and its data. Callbacks allow you to trigger logic before or after an alteration of an object's state.


1 Answers

Technically you only need to use the self in front of the assignment methods. This is necessary to differentiate between a instance method with trailing = and an assignment to a local variable.

like image 57
nasmorn Avatar answered Oct 05 '22 23:10

nasmorn