Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do we declare attributes of a rails model?

I come from a Java background and I have started learning Ruby on Rails. Consider the following code mentioned in http://guides.rubyonrails.org/active_record_basics.html

class Product < ActiveRecord::Base
end

The guide mentions that this creates a model Product mapped to a table products (using the pluralized mechanism of ruby). It also mentions, 'By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model.'

But we did not declare any attributes inside the model Product. How does it know what are its attributes?

One assumption: Every attribute of table is made as an attribute of model. Is it true? Then, do we create the SQL table first? If I change the table later on (adding new columns, say) does it also change my model dynamically?

like image 275
whitehat Avatar asked Jan 10 '16 03:01

whitehat


1 Answers

The important distinction is that we're talking about ActiveRecord models, i. e. subclasses (direct and indirect) of ActiveRecord::Base, those that use its persistence mechanism. The following is not true for Rails models in general. But then again, for non-AR models the question makes no sense :)

Every attribute of table is made as an attribute of model. Is it true?

Yes.

Then, do we create the SQL table first?

Exactly. rails g model creates a model file and a migration that contains a declaration for a table behind the model. So before using your model, you have to run the migration first.

If I change the table later on (adding new columns, say) does it also change my model dynamically?

Now that's tricky. It's most certainly true if the application is reloaded after the changes (e. g. in development mode this happens every now and then), since the model class will be reconstructed. So the answer is yes, most of the time.

This is, however, only about the internal structures of the model class (visible in e. g. Model.columns) you don't always have to care about. When fetching data, all the columns of the result set will be mapped to attributes of the model objects. So this keeps even custom columns you specify in SELECTs:

Thing.select(:id, "1 AS one").first.attributes
#> SELECT  "things"."id", 1 AS one FROM "things"  ORDER BY "things"."id" ASC LIMIT 1
# => {"id"=>1, "one"=>1}
like image 169
D-side Avatar answered Sep 28 '22 07:09

D-side