Model in Ruby on Rails
Last Updated: August 27, 2020
Lets see how to create a model on Ruby on Rails
I want to create Product and Category models. Product model has a reference to Category model
So I first create the model Category
rails g model category category_name
Your migrated file @db\migrate location
class CreateCategories < ActiveRecord::Migration[6.0] def change create_table :categories do |t| t.string :category_name t.timestamps end end end
and then run the migrate
rake db:migrate
Second I will create the Product
rails g model product product_name sku category:references
You can see the migrated file
class CreateProducts < ActiveRecord::Migration[6.0] def change create_table :products do |t| t.string :product_name t.string :sku t.references :categories, null: false, foreign_key: true t.timestamps end end end
and then run the migrate
rake db:migrate
/usr/local/Cellar/ruby/2.6.5/bin/ruby /Users/Niro/RubymineProjects/untitled/bin/rails g model product product_name sku album:references
/usr/local/Cellar/ruby/2.6.5/bin/ruby /Users/Niro/RubymineProjects/untitled/bin/rails
Rails model generator saves time
List of available types
integer
primary_key
decimal
float
boolean
binary
string
text
date
time
datetime
timestamp