Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR models don't seem to act like a Ruby class?

If I have a RoR model person.rb as follows:

class Person < ActiveRecord::Base
  attr_accessible :first_name, :last_name

  validates :first_name, presence: true
  validates :last_name, presence: true
end

I don't seem to be able to do any of the below:

@full_name = @first_name + " " + @last_name

or

def full_name
   @first_name + " " + @last_name 
end

To my understanding, both of those should work with a regular ruby class.

I did a bit of reading and the below seems to be the way to go:

def full_name
    self.first_name + " " + self.last_name
end

I can make this work but I really would like to understand why I can't seem to be able to reference instance variables in any way (nor create new ones).

Does ActiveRecord::Base do something extremely funny to instance variables? Does it limit a model (class Person in this case) to be nothing more then just a wrapper around what's in the DB?

I can't seem to define an attr_accessor either... but I can set first_name and last_name just fine (not only via mass assignment but also p = Person.new; p.first_name = foo)

If anyone could please shed some light on this that would be greatly appreciated.

Many thanks,

like image 993
dreamwalker Avatar asked Dec 06 '22 11:12

dreamwalker


2 Answers

ActiveRecord model attributes are stored in an instance variable called @attributes, which is a hash. The getters and setters are defined for you to access this variable.

By the way, this is the recommended way to concatenate strings in Ruby:

"#{first_name} #{last_name}"

There is a built-in "to_s" method (on most objects) that will allow you to insert them directly into strings this way. While you couldn't do this: "string " + 1 without raising an error, you can do this: "string #{1}"

like image 94
Zach Kemp Avatar answered Dec 14 '22 22:12

Zach Kemp


Active Record doesn't store database attributes in individual instance variables, which is why you have to use the accessors it provides and why the accessors generated by attr_accessor don't work.

Instead Active Record stores the attributes in a hash (before and after typecasting), however this is an implementation detail that you shouldn't need to worry about.

like image 23
Frederick Cheung Avatar answered Dec 14 '22 22:12

Frederick Cheung