Skip to content

Instantly share code, notes, and snippets.

@osazemeu
Created February 9, 2024 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osazemeu/5be06b1e9ef761b4cee2ce80baf4c4b8 to your computer and use it in GitHub Desktop.
Save osazemeu/5be06b1e9ef761b4cee2ce80baf4c4b8 to your computer and use it in GitHub Desktop.
Qualified Andela Ruby
class CreateAlbums < ActiveRecord::Migration[6.1]
def change
create_table "albums", force: :cascade do |t|
t.string "title"
t.string "performer"
t.integer "cost"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "last_purchased_at"
t.integer "last_purchased_by"
end
end
end
class Album < ApplicationRecord
has_many :purchases
# Validates presence of title, performer, and cost
validates :title, :performer, :cost, presence: true
# Validates cost is a positive integer
validates :cost, numericality: { only_integer: true, greater_than: 0 }
end
class Purchase < ApplicationRecord
belongs_to :album
belongs_to :user
validates :album_id, :user_id, presence: true
after_create :update_album_purchase_info, :increment_user_total_purchases
private
def update_album_purchase_info
album.update(last_purchased_at: Time.current, last_purchased_by: user.id)
end
def increment_user_total_purchases
user.increment!(:total_purchases)
end
end
class User < ActiveRecord::Base
has_many :purchases
validates :name, presence: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment