1

So I have a Model class like this:

attr_accessible :email, :firstname, :lastname, :phones_attributes

and even validations in that model like this:

 validates :firstname, presence: true

Notice all of them are using that ":" symbol before the variable names.

But then in that Model I have a method like this:

  def name
    [firstname, lastname].join(' ')
  end

So how come we didn't need to type those ":" before variable names this time? What's the difference?

2 Answers2

3

You see, what you pass to attr_accessor is not actually a variable, but rather, the name of a variable. The name of a variable is a symbol, and :name is the literal syntax for symbols. In your name method, you are actually using a variable, not just it's name, and as such, no :.

In more detail, attr_accessor is never using the variable directly. Rather, it is using methods that get the variable by name. So, it needs the name, rather than the variable.

Linuxios
  • 34,849
  • 13
  • 91
  • 116
1

Look at the symbols as simple string denoting something in a "Rails's way". So this is same as:

attr_accessible "email", "firstname", "lastname", "phones_attributes"

However in the instance method name, firstname and lastname are actually understood as model_object.firstname, model_object.lastname etc. Hence, no colon.

atmaish
  • 2,495
  • 3
  • 22
  • 25