Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use "self" to access ActiveRecord/Rails model properties?

Throughout my application self. is not necessary to refer to a User's name. name works fine.

Why does the following code require self to work as intended?

class User< ActiveRecord::Base
    before_save :validate_name

def validate_name
    if self.name.nil? || self.name.empty?
        self.name= "Mr. No Name"
    end
end

By the way, I know that validates_presence_of can be used to prevent the save, but I want to save with a default if no name is given.

Rails 3.0.7.

like image 536
B Seven Avatar asked Apr 12 '12 16:04

B Seven


People also ask

What does ActiveRecord base do?

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

What is Rails ActiveRecord?

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 ActiveRecord naming convention?

Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns. Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id , order_id ).


1 Answers

Often the use of self is to force Ruby to recognize that as a method call and not mis-interpret it as a variable. Without prior knowledge of a method called day=, then day = "x" looks to Ruby like a variable assignment. self.day = "x" is always a method call.

The reason this is trouble is because the name and name= methods are added dynamically after the User class file has been parsed. The first thing Rails does when using a model is make methods for the associated database fields, but this happens after your user.rb file is parsed.

like image 187
tadman Avatar answered Oct 03 '22 05:10

tadman