Last active
October 16, 2016 15:36
-
-
Save lkrych/96875a4a95612d40df80bbc48c099a17 to your computer and use it in GitHub Desktop.
CRUD functionality in the movies controller
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 MoviesController < ApplicationController | |
#NOTE: you can ignore show and index, we are only going to test the CRUD functions. | |
def movie_params | |
params.require(:movie).permit(:title, :rating, :description, :release_date) | |
end | |
def show | |
id = params[:id] # retrieve movie ID from URI route | |
@movie = Movie.find(id) # look up movie by unique ID | |
# will render app/views/movies/show.<extension> by default | |
end | |
def index | |
sort = params[:sort] || session[:sort] | |
case sort | |
when 'title' | |
ordering,@title_header = {:title => :asc}, 'hilite' | |
when 'release_date' | |
ordering,@date_header = {:release_date => :asc}, 'hilite' | |
end | |
@all_ratings = Movie.all_ratings | |
@selected_ratings = params[:ratings] || session[:ratings] || {} | |
if @selected_ratings == {} | |
@selected_ratings = Hash[@all_ratings.map {|rating| [rating, rating]}] | |
end | |
if params[:sort] != session[:sort] or params[:ratings] != session[:ratings] | |
session[:sort] = sort | |
session[:ratings] = @selected_ratings | |
redirect_to :sort => sort, :ratings => @selected_ratings and return | |
end | |
@movies = Movie.where(rating: @selected_ratings.keys).order(ordering) | |
end | |
def new | |
# default: render 'new' template | |
end | |
def create | |
@movie = Movie.create!(movie_params) | |
flash[:notice] = "#{@movie.title} was successfully created." | |
redirect_to movies_path | |
end | |
def edit | |
@movie = Movie.find params[:id] | |
end | |
def update | |
@movie = Movie.find params[:id] | |
@movie.update_attributes!(movie_params) | |
flash[:notice] = "#{@movie.title} was successfully updated." | |
redirect_to movie_path(@movie) | |
end | |
def destroy | |
@movie = Movie.find(params[:id]) | |
@movie.destroy | |
flash[:notice] = "Movie '#{@movie.title}' deleted." | |
redirect_to movies_path | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment