Created
February 9, 2024 22:07
-
-
Save osazemeu/5be06b1e9ef761b4cee2ce80baf4c4b8 to your computer and use it in GitHub Desktop.
Qualified Andela Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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