GMsoF GMsoF - 17 days ago 7
Ruby Question

How Rails resolve model attribute since they not defined in the model?

I am started to learn Ruby and Rails, sometime the "Convention over configuration" kind of killing me...

OK, I created a

User
model in Rails via the Rails command.
User
model created with some attributes too, like
name
and
age
.

But when I open the
user.rb
:

class User < ApplicationRecord
end


It only has these. I can't find the
attr_accessor
. So I keep searching, I found that the attributes name and method is kept somewhere, so basically I still can create the object as usual and refer to the attribute
user.name
and
user.age
.

My question is, where are the attribute kept in Rails? And how is this happening? I don't think the attribute is kept in superclass
ApplicationRecord
too, I opened
application_record.rb
:

class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end


So where are those attributes kept? And how Ruby resolve the attribute like this? I would like to know the mechanism behind.

Answer

ActiveRecord doesn't modify your code, it doesn't alter how things are implemented. What it does instead, which is a common pattern in Ruby, is define methods dynamically. This is often referred to as "meta-programming" since your code effectively writes code. Note that it doesn't literally write code, it's only when the program's loaded in memory that it transforms itself.

The columns are usually automatically discovered by running a SQL command like SHOW FIELDS to determine the structure and types. Then these methods get generated accordingly.

If you want to know the mechanism you can always read the ActiveRecord source code, though keep in mind it does a lot of things and may be a little difficult to navigate at times.

Comments