<repo_name>mellauyellow/Music-App<file_sep>/app/models/album.rb
class Album < ActiveRecord::Base
  ALBUM_STATUS = %w(live studio)

  validates :band_id, :name, :status, presence: true
  validates :status, inclusion: ALBUM_STATUS

  belongs_to :band,
    class_name: :Band,
    primary_key: :id,
    foreign_key: :band_id

  has_many :tracks,
    class_name: :Track,
    primary_key: :id,
    foreign_key: :album_id,
    dependent: :destroy
end
<file_sep>/app/controllers/albums_controller.rb
class AlbumsController < ApplicationController
  before_action :require_login
  
  def create
    @album = Album.new(album_params)

    if @album.save
      redirect_to band_url(@album.band_id)
    else
      flash.now[:errors] = @album.errors.full_messages
      render :new
    end
  end

  def new
    @album = Album.new
    @bands = Band.all
    @current_band = Band.find_by_id(params[:band_id])
    render :new
  end

  def update
    @album = current_album

    if @album.update_attributes(album_params)
      redirect_to band_url(@album.band_id)
    else
      flash.now[:errors] = @album.errors.full_messages
      render :edit
    end
  end

  def destroy
    @album = current_album
    band_id = @album.band_id
    @album.destroy

    redirect_to band_url(band_id)
  end

  def edit
    @album = current_album
    @current_band = Band.find_by_id(@album.band_id)
    @bands = Band.all

    render :edit
  end

  def show
    @album = current_album
    @current_band = Band.find_by_id(@album.band_id)
  end

  private

  def album_params
    params.require(:album).permit(:band_id, :status, :name)
  end
end
<file_sep>/app/models/track.rb
class Track < ActiveRecord::Base
  TRACK_STATUS = %w(bonus regular)

  validates :album_id, :name, :status, presence: true
  validates :status, inclusion: TRACK_STATUS

  belongs_to :album,
    class_name: :Album,
    primary_key: :id,
    foreign_key: :album_id

  has_one :band,
    through: :album,
    source: :band
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  helper_method :current_user, :logged_in?

  def current_user
    return nil unless session[:session_token]
    @current_user ||= User.find_by(session_token: session[:session_token])
  end

  def log_in_user!(user)
    session[:session_token] = user.reset_session_token!
  end

  def logout(user)
    user.reset_session_token!
    session[:session_token] = nil
  end

  def logged_in?
    !current_user.nil?
  end

  def current_band
    @current_band ||= Band.find_by_id(params[:id])
  end

  def current_album
    @current_album ||= Album.find_by_id(params[:id])
  end

  def current_track
    @current_track ||= Track.find_by_id(params[:id])
  end

  def require_login
    redirect_to new_session_url if current_user.nil?
  end
end
