Skip to content

Instantly share code, notes, and snippets.

@jmercedes
Last active December 12, 2015 03:08
Show Gist options
  • Save jmercedes/4704053 to your computer and use it in GitHub Desktop.
Save jmercedes/4704053 to your computer and use it in GitHub Desktop.
module ApplicationHelper
def sortlist (column, title = nil, filter, css_class)
title ||= column.titleize
css_id = column == :sort_column ? "hilite" : "#{column}_header"
direction = column == :sort_column && :sort_direction == "asc" ? "desc" : "asc"
link_to title, {:sort => column, :direction => direction, :ratings => filter}, {:id => css_id}
end
def th_class (column)
css_class = column == params[:sort] ? "hilite" : nil
end
end
helper_method :sort_column, :sort_direction
def index
@movies = Movie.order(sort_column + " " + sort_direction).filter(filter_selection)
@all_ratings = Movie.all_ratings
@selected_ratings = (params[:ratings].present? ? params[:ratings] : [])
end
end
....
def filter_selection
params[:ratings] == nil ? Movie.all_ratings : params[:ratings]
end
def sort_column
Movie.column_names.include?(params[:sort]) ? params[:sort] : "id"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
-# This file is app/views/movies/index.html.haml
%h1 All Movies
= form_tag movies_path, :method => :get do
Include:
- @all_ratings.each do |rating|
= rating
= check_box_tag( "ratings[#{rating}]", " ", @selected_ratings.include?(rating), :id => "ratings_#{rating}")
= submit_tag 'Refresh', :id => "ratings_submit"
%table#movies
%thead
%tr
%th{:class => th_class("title")}= sortlist "title", "Movie Title", @selected_ratings, "title_header"
%th Rating
%th{:class => th_class("release_date")}= sortlist "release_date", "Release Date", @selected_ratings, "release_date_header"
%th More Info
%tbody
- @movies.each do |movie|
%tr
%td= movie.title
%td= movie.rating
%td= movie.release_date
%td= link_to "More about #{movie.title}", movie_path(movie)
= link_to 'Add new movie', new_movie_path
class Movie < ActiveRecord::Base
def self.all_ratings
self.select(:rating).map(&:rating).uniq
end
def self.filter(selection)
begin
self.where(:rating => selection.keys)
rescue
self.where(:rating => selection)
end
end
end
http://secret-beach-3782.herokuapp.com/movies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment