diff --git a/app/controllers/movies_controller.rb b/app/controllers/movies_controller.rb index 2a235e2..9f6da93 100644 --- a/app/controllers/movies_controller.rb +++ b/app/controllers/movies_controller.rb @@ -2,8 +2,14 @@ class MoviesController < ApplicationController before_action :set_movie, only: %i[ show edit update destroy ] # GET /movies or /movies.json + def index - @movies = Movie.all + # Fetch sorting parameters from the URL + sort_attribute = params[:attribute] || 'title' + sort_order = params[:order] || 'asc' + + # Fetch and sort movies based on parameters + @movies = Movie.sorted_by(sort_attribute, sort_order) end # GET /movies/1 or /movies/1.json @@ -19,6 +25,9 @@ def new def edit end + def sort + + end # POST /movies or /movies.json def create @movie = Movie.new(movie_params) @@ -67,4 +76,10 @@ def set_movie def movie_params params.require(:movie).permit(:title, :rating, :description, :release_date) end + + def sort + respond_to do |format| + format.html { redirect_to movies_url, notice: "Sorting is yet to be done" } + end + end end diff --git a/app/models/movie.rb b/app/models/movie.rb index 4b0507d..456c12a 100644 --- a/app/models/movie.rb +++ b/app/models/movie.rb @@ -1,2 +1,15 @@ class Movie < ActiveRecord::Base -end \ No newline at end of file + # Class method to sort movies based on the attribute and order + def self.sorted_by(attribute, order) + valid_attributes = %w[title rating release_date] # Allowed attributes for sorting + valid_order = %w[asc desc] # Allowed orders + + # Default values if parameters are invalid + attribute = 'title' unless valid_attributes.include?(attribute) + order = 'asc' unless valid_order.include?(order) + + # Apply sorting using ActiveRecord's `order` method + order("#{attribute} #{order}") + end + end + \ No newline at end of file diff --git a/app/views/movies/_movie.html.erb b/app/views/movies/_movie.html.erb index a580202..ab46c0c 100644 --- a/app/views/movies/_movie.html.erb +++ b/app/views/movies/_movie.html.erb @@ -2,10 +2,10 @@
<%= "Title: #{movieshow.title} " %>
+<%= "Rating: #{movieshow.rating} " %>
+<%= "Release Date: #{movieshow.release_date} " %>
+<%= "Description: #{movieshow.description} " %>
+ + +Title | -Rating | -Release date | -Show this movie | + ++ <%= link_to 'Title', movies_path(attribute: 'title', order: params[:order] == 'asc' ? 'desc' : 'asc') %> + <% if params[:attribute] == 'title' %> + <%= params[:order] == 'asc' ? '▲' : '▼' %> + <% end %> + | ++ <%= link_to 'Rating', movies_path(attribute: 'rating', order: params[:order] == 'asc' ? 'desc' : 'asc') %> + <% if params[:attribute] == 'rating' %> + <%= params[:order] == 'asc' ? '▲' : '▼' %> + <% end %> + | ++ <%= link_to 'Release Date', movies_path(attribute: 'release_date', order: params[:order] == 'asc' ? 'desc' : 'asc') %> + <% if params[:attribute] == 'release_date' %> + <%= params[:order] == 'asc' ? '▲' : '▼' %> + <% end %> + | + + +Show this movie |
---|