I was using Ryan Bates's source code for railscasts #141 in order to create a simple shopping cart. In one of the migrations, he lists
class CreateProducts < ActiveRecord::Migration def self.up create_table :products do |t| t.belongs_to :category t.string :name t.decimal :price t.text :description t.timestamps end end def self.down drop_table :products end end
Here is the Product model:
class Product < ActiveRecord::Base belongs_to :category end
What is the t.belongs_to :category
line? Is that an alias for t.integer category_id
?
t. references tells the database to make a column in the table. foreign_key: true tells the database that the column contains foreign_key from another table. belongs_to tells the Model that it belongs to another Model.
A migration means that you move from the current version to a newer version (as is said in the first answer). Using rake db:migrate you can apply any new changes to your schema. But if you want to rollback to a previous migration you can use rake db:rollback to nullify your new changes if they are incorrectly defined.
Every time a migration is generated using the rails g migration command, Rails generates the migration file with a unique timestamp. The timestamp is in the format YYYYMMDDHHMMSS . Whenever a migration is run, Rails inserts the migration timestamp into an internal table schema_migrations .
A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.
The t.belongs_to :category
is just a special helper method of rails passing in the association.
If you look in the source code belongs_to
is actually an alias of references
$ rails g migration AddUserRefToProducts user:references
this generates:
class AddUserRefToProducts < ActiveRecord::Migration def change add_reference :products, :user, index: true end end
http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With