Models
Create a Model
bash
bin/rails g model Supplier name:string
bin/rails g model Product name:string:index sku:string{10}:uniq count:integer description:text supplier:references popularity:float 'price:decimal{10,2}' available:boolean availableSince:datetime image:binary
bin/rails g scaffold Product name:string:index sku:string{10}:uniq count:integer description:text supplier:references popularity:float 'price:decimal{10,2}' available:boolean availableSince:datetime image:binary
The Migration for creating a table
ruby
class CreateSuppliers < ActiveRecord::Migration[6.1]
def change
create_table :suppliers do |t|
t.string :name
t.timestamps
end
end
end
class CreateProducts < ActiveRecord::Migration[6.1]
def change
create_table :products do |t|
t.string :name
t.string :sku, limit: 10
t.integer :count
t.text :description
t.references :supplier, null: false, foreign_key: true
t.float :popularity
t.decimal :price, precision: 10, scale: 2
t.boolean :available
t.datetime :availableSince
t.binary :image
t.timestamps
end
add_index :products, :name
add_index :products, :sku, unique: true
end
end
Destroy a Model
bash
bundle exec rails db:rollback
rails destroy model Supplier
scopes
where
select
include
belongs_to
has_many
has_one
private
application record
before_validation
validates_presence_of
validates_uniqueness_of
before_validation
validate
enum
ActiveRecord::Base
require
after_update
module
include
freeze
select
map
where
Scopes
A scope is a query that you defined in your models that returns an active record relation, which allows you to chain queries together.
ruby
class Fruit < ApplicationRecord
scope :with_juice, -> { where("juice > 0") }
end
Scope Implementation
Fruit.with_juice.with_round_shape.first(3)