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

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

class Person < ActiveRecord::Base attr_accessible :first_name, :last_name validates :first_name, presence: true validates :last_name, presence: true end 

I can't seem to do anything:

 @full_name = @first_name + " " + @last_name 

or

 def full_name @first_name + " " + @last_name end 

As far as I understand, both of them should work with the usual class of rubies.

I read a little, and it seems to be the way to go:

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

I can do this work, but I really would like to understand why I cannot in any way refer to instance variables (and not create new ones).

Does ActiveRecord :: Base use something extremely funny for instance variables? Does it limit the model (the Person class in this case) is nothing but a wrapper around what is in the database?

I can't determine attr_accessor either ... but I can set first_name and last_name just fine (not only through bulk assignment, but also p = Person.new; p.first_name = foo)

If someone can shed light on this, that would be very grateful.

Thank you very much,

+4
source share
2 answers

ActiveRecord model attributes are stored in an instance variable called @attributes , which is a hash. Recipients and setters are defined 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. Although you could not do this: "string " + 1 without raising the error, you can do this: "string #{1}"

+10
source

An active record does not store database attributes in separate instance variables, so you should use the recipients that it provides, and why accessors created with attr_accessor do not work.

Instead, Active Record stores attributes in a hash (before and after type casting), however these are implementation details that you don't need to worry about.

+5
source

Source: https://habr.com/ru/post/1440152/


All Articles