movies_controller.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. class MoviesController < ApplicationController
  2. def movie_params
  3. params.require(:movie).permit(:title, :rating, :description, :release_date)
  4. end
  5. def show
  6. id = params[:id] # retrieve movie ID from URI route
  7. @movie = Movie.find(id) # look up movie by unique ID
  8. # will render app/views/movies/show.<extension> by default
  9. end
  10. def index
  11. sort = params[:sort] || session[:sort]
  12. if sort == :title or sort == :release_date
  13. session[:sort] = sort || {}
  14. end
  15. @title_header = 'hilite' if sort == "title"
  16. @release_date_header = 'hilite' if sort == "release_date"
  17. all_ratings = Movie.all.select(:rating).group(:rating).order(:rating)
  18. @all_ratings = all_ratings.map {|d| d.rating}
  19. if params[:ratings] != nil
  20. session[:ratings] = params[:ratings].map {|i, v| i}
  21. @ratings_array = session[:ratings]
  22. else
  23. if params[:sort] == nil && params[:controller] == :movies
  24. @ratings_array = @all_ratings
  25. session[:ratings] = @ratings_array || @all_ratings
  26. else
  27. @ratings_array = session[:ratings] || @all_ratings || {}
  28. end
  29. end
  30. if params[:sort] != session[:sort] or params[:ratings] != session[:ratings]
  31. session[:sort] = sort
  32. session[:ratings] = @ratings_array
  33. if @ratings_array == {}
  34. redirect_to :sort => sort, :ratings => @all_ratings and return
  35. else
  36. redirect_to :sort => sort, :ratings => @ratings_array and return
  37. end
  38. end
  39. @movies = Movie.all.where(rating: @ratings_array)
  40. @movies = @movies.order(sort)
  41. end
  42. def new
  43. # default: render 'new' template
  44. end
  45. def create
  46. @movie = Movie.create!(movie_params)
  47. flash[:notice] = "#{@movie.title} was successfully created."
  48. redirect_to movies_path
  49. end
  50. def edit
  51. @movie = Movie.find params[:id]
  52. end
  53. def update
  54. @movie = Movie.find params[:id]
  55. @movie.update_attributes!(movie_params)
  56. flash[:notice] = "#{@movie.title} was successfully updated."
  57. redirect_to movie_path(@movie)
  58. end
  59. def destroy
  60. @movie = Movie.find(params[:id])
  61. @movie.destroy
  62. flash[:notice] = "Movie '#{@movie.title}' deleted."
  63. redirect_to movies_path
  64. end
  65. end