GMsoF GMsoF - 1 year ago 56
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

model in Rails via the Rails command.
model created with some attributes too, like

But when I open the

class User < ApplicationRecord

It only has these. I can't find the
. 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

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
too, I opened

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download