04. Model validation, association - max-borisov/ihub-bookshelf GitHub Wiki

This is how your models folder should look like:

Models folder

We are going to update models by specifying associations with other models and validation rules.

book.rb

class Book < ActiveRecord::Base
  has_many :reviews, dependent: :destroy

  validates :title, :author, :pub_date, :price, :isbn, :description, presence: true
  validates :title, :author, length: { maximum: 150 }
  validates :isbn, length: { maximum: 12 }, format: { with: /[\d\-]+/ }
  validates :amazon_id, length: { maximum: 50 }, format: { with: /[\dA-Z]+/ }
  validates :isbn, :amazon_id, uniqueness: { message: 'is not unique' }
  validates :price, numericality: true
end

review.rb

class Review < ActiveRecord::Base
  belongs_to :user
  belongs_to :book
end

user.rb

class User < ActiveRecord::Base
  has_many :reviews, dependent: :destroy
  has_many :shopping_cart_items, dependent: :destroy
  has_many :books, through: :shopping_cart_items
  has_many :orders, dependent: :destroy

  validates :name, presence: true
end

shopping_cart_item.rb

class ShoppingCartItem < ActiveRecord::Base
  belongs_to :user
  belongs_to :book
end

order.rb

class Order < ActiveRecord::Base
  belongs_to :user
  has_many :order_items, dependent: :destroy

  validates :user_id, :total_price, presence: true
end

order_item.rb

class OrderItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :book
end

Helpful links