This command:
rails g model Product name quantity:integer
generates a model Product
with two fields: name
, which is a string, and quantity
, which is an integer.
Product
?Product
instance in a controller:eg:
def new
@product = Product.new
end
where is the initialize
method called?
To be a little more precise...
When you do:
rails g model Product name quantity:integer
You are not adding a product table to your database. You are creating a migration
and a model
(and perhaps some tests, depending...). You'll see something like:
invoke active_record
create db/migrate/20171129070104_create_products.rb
create app/models/product.rb
When you do:
rake db:migrate
THEN you're adding a table to your database. You'll see something like:
== 20171129070623 CreateProducts: migrating ==============
-- create_table(:products)
-> 0.0179s
== 20171129070623 CreateProducts: migrated (0.0180s) =====
Once migrated, your products
table will have columns named name
and quantity
.
To your questions:
Are the fields instance variables of Product?
Roughly, yes. An instance of Product
will have attributes for name
and quantity
. So, if you do (in console):
p = Product.new
You will see:
> p = Product.new
=> #<Product id: nil, name: nil, quantity: nil, created_at: nil, updated_at: nil>
If so, when and where are they initialized?
Instance attributes are initialized when calling new
on a model class. If you call new
with no arguments, then the attributes are initialized to nil
.
You can also call new
with arguments, such as:
> Product.new(name: 'foo', quantity: 2)
=> #<Product id: nil, name: "foo", quantity: 2, created_at: nil, updated_at: nil>
Where are they initialized? Anywhere you want. There are varying ideas about practices that are "good" and practices that are "bad". But, that's a much longer discussion.
Personally, I never interact (e.g., initialize, save, update, delete) with my models in my controllers
or views
. I have a custom class called managers
and that is the only place I interact with my models. But, I am very odd in this regard and you should consider my practice "anomalous".
When a creating a Product instance in a controller, where is the initialize method called?
As pointed out elsewhere, it is called when new
is called. There are some subtleties, and you might want to look into ActiveRecord::Callbacks
.
Also, as pointed out elsewhere, you can override initialize
for any number of reasons.
By the way, new
and initialize
are not unique to models. It is very common to use them in plain old ruby objects.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments