Skip to content

Instantly share code, notes, and snippets.

@seanreed1111
Created August 26, 2016 19:04
Show Gist options
  • Save seanreed1111/a5b3c4ae487d219272230f6224cb2a07 to your computer and use it in GitHub Desktop.
Save seanreed1111/a5b3c4ae487d219272230f6224cb2a07 to your computer and use it in GitHub Desktop.
class Album < ActiveRecord::Base
belongs_to :user
belongs_to :artist
validates :name, presence: true
validates :name, uniqueness: {scope: :artist_id,
message: "only one album of same name per artist"}
accepts_nested_attributes_for :artist
has_many :songs, dependent: :destroy
accepts_nested_attributes_for :songs
has_many :favorites, as: :favoritable, dependent: :destroy #polymorphic
class AlbumsController < ApplicationController
before_action :set_user!
before_action :set_album, only: [:show, :edit, :update, :destroy]
def index
@albums = @user.albums
end
def show
@songs = @album.songs
end
def new
@album = @user.albums.new
end
def create
@album = @user.albums.new(album_params)
artist_name = album_params[:artist_name_field]
artist = Artist.find_or_create_by(name: artist_name)
if artist.valid?
@album.artist_id = artist.id
end
if @album.save
redirect_to albums_path, notice: 'Album was successfully created.'
else
render :new
end
end
def edit
@songs = @album.songs
end
def update
artist_name = album_params[:artist_name_field]
artist = Artist.find_or_create_by(name: artist_name)
if ((artist.valid?) && (@album.artist_id != artist.id))
@album.artist_id = artist.id
end
if @album.update(album_params)
redirect_to albums_path, notice: 'Album was successfully updated.'
else
render :edit
end
end
def destroy
@album.destroy
respond_to do |format|
format.html {redirect_to albums_url, notice: 'Album was successfully destroyed.'}
format.js
end
end
private
def set_user!
authenticate_user!
@user = current_user
end
# Use callbacks to share common setup or constraints between actions.
def set_album
@album = Album.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def album_params
params.require(:album).permit(:name, :artist_name_field)
end
end
class Artist < ActiveRecord::Base
has_many :albums, dependent: :nullify
has_many :favorites, as: :favoritable, dependent: :destroy #polymorphic
validates :name, presence: true
validates :name, uniqueness: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment