Why don't I see more constructors in rails models
It seems that I rarely, if ever, see or use a ruby constructor in a rails model.
My assumption is that because rails sets up so much stuff for you the need for initialization code is much lower.
Aren开发者_如何学JAVA't there any good use cases for a constructor in a model though?
There's nothing wrong with a constructor, just that they're hardly ever needed. The main reason for a constructor would be for setting up default values. Setting default attributes, is easily done at the database level
add_column :users, :admin, :boolean, :default => false
The main other thing that might be needed would be the existence/creation of an association model, this can be done either in a constructor/initializer, but what's more common is to use rails hooks to set a before_create :populate_children, :ensure_parent_exists
(where populate_children, and ensure_parent_exists are private model methods) or something like that. This approach means that any initialization logic can be divided into logical methods (e.g. separate methods for each bit of initialization), and some can additionally be called at other times too after_save :ensure_parent_exists
, and thus allows for more flexibility
There's no reason you couldn't. Most of the important stuff is handled for you by ActiveRecord, but if you had some sort of specific initialization code you wanted to run, you could define your own constructor - just make sure it calls super
.
精彩评论