Why I do not see more designers in rail models

It seems that I rarely, if ever, see or use the ruby ​​constructor in a rail model.

My guess is that since rails set so many things for you, the need for initialization code is much lower.

Are there any good use cases for the constructor in the model, though?

+4
source share
2 answers

There is nothing wrong with a constructor, simply because they are almost never needed. The main reason for the constructor is to set default values. Setting attributes by default is easy at the database level

add_column :users, :admin, :boolean, :default => false 

. Another important thing that may be required is the creation / creation of an association model, this can be done either in the constructor / initializer, but in that it is more common to use rail hooks to set before_create :populate_children, :ensure_parent_exists (where populate_children and secure_parent_exists are private methods of the model) or something like that. This approach means that any initialization logic can be divided into logical methods (for example, separate methods for each initialization bit), and some can be additionally called at other times after_save :ensure_parent_exists and, thus, provide greater flexibility

+4
source

There is no reason why you could not. Most important things are handled by ActiveRecord for you, but if you have any specific initialization code that you want to run, you could define your own constructor - just make sure it calls super .

+1
source

All Articles