Wednesday, October 5, 2022
HomeRuby On RailsEnergetic Document Tips | Drifting Ruby

Energetic Document Tips | Drifting Ruby


# Terminal

bin/rails g mannequin product title class sku in_stock:boolean
# db/migrate/20220501015917_create_products.rb
class CreateProducts < ActiveRecord::Migration[7.0]
  def change
    create_table :merchandise do |t|
      t.string :title
      t.string :class
      t.string :sku, index: { distinctive: true }
      t.boolean :in_stock, default: true

      t.timestamps
    finish
  finish
finish
# fashions/product.rb
class Product < ApplicationRecord
  attr_readonly :sku
finish
# Rails Console
product = Product.first
product.sku = "changedsku"
product.save # document updates, however sku attribute is ignored
# Rails Console
merchandise = [
  { name: 'Apple 14" Macbook Pro (2021)', category: "Laptop", sku: "MKGR3LL", in_stock: true },
  { name: 'Apple 16" Macbook Pro (2021)', category: "Laptop", sku: "MK1E3LL", in_stock: true },
  { name: 'Apple Mac Mini (2020)', category: "Desktop", sku: "MGNR3LL", in_stock: true },
  { name: 'Apple Mac Studio (2022)', category: "Desktop", sku: "MJMW3LL", in_stock: true }
]

Product.insert_all(merchandise)

laptops = [
  { name: 'Apple 14" Macbook Pro (2021)', sku: "MKGR3LL", in_stock: true },
  { name: 'Apple 16" Macbook Pro (2021)', sku: "MK1E3LL", in_stock: true }
]

Product.create_with(class: "Laptop computer").insert_all(laptops)
# Rails Console

desktops = [
  { name: 'Apple Mac Mini (2020)', category: "Desktop", sku: "MGNR3LL", in_stock: false },
  { name: 'Apple Mac Studio (2022)', category: "Desktop", sku: "MJMW3LL", in_stock: true }
]

Product.upsert_all(desktops, update_only: [:in_stock], unique_by: [:sku])
# Rails Console
product = Product.first

product.toggle(:in_stock)
product.save

product.toggle!(:in_stock)
# Terminal
rails g mannequin car title kind
# fashions/automotive.rb
class Automotive < Automobile
  WHEELS = 4
finish
# fashions/motorbike.rb
class Motorbike < Automobile
  WHEELS = 2
finish
# Rails Console
Automotive.create(title: "Civic")
Motorbike.create(title: "Hayabusa")

car = Motorbike.first
car.turns into(Automotive)

car.turns into!(Automotive)
car.save
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments