-
Notifications
You must be signed in to change notification settings - Fork 6
Session 5 Enhancing the UI
First, to make a sort column I show a way to do this without ajax.
Add to the application controller a method sort_order. This is used to modify the db request to order by the sort column (app/controllers/application_controller.rb inside the ApplicationController class)
def sort_order(default)
"#{(params[:c] || default.to_s).gsub(/[\s;'\"]/,'')} #{params[:d] == 'down' ? 'DESC' : 'ASC'}"
end
Next, the controller needs to order movies appropriately by using the sort column that has been passed in; created_at is used as a default sort order. (app/controllers/movies_controller.rb, the index method)
def index
@movies = Movies.all(:order => sort_order('created_at'))
end
Add a helper to be used by the view to render the link, including logic to reverse the sort on alternating clicks (app/helpers/application_helper.rb, a new method sort_link)
def sort_link(title, column, options = {})
condition = options[:unless] if options.has_key?(:unless)
sort_dir = params[:d] == 'up' ? 'down' : 'up'
link_to_unless condition, title, request.parameters.merge( {:c => column, :d => sort_dir} )
end
Use this helper to render the column helper in the view (app/views/movies/index.html.erb)
change
<th class="col">Synopsis</th>
to
<th class="col"><%= sort_link 'Synopsis', :synopsis %></th>
For a search, add code to render the field using a GET rather than a POST form, to make it bookmarkable (app/views/movies/index.html.erb before the main table)
<% form_tag(movies_path, :method => "get") do %>
<%= text_field_tag(:s) %>
<%= submit_tag("Search", :name => nil) %>
<% end %>
This goes back to the index method which should now filter the movies it returns:
def index
if params[:s]
@movies = Movies.all(:conditions => ['title like ?', "%#{params[:s]}%"])
else
@movies = Movies.all
end
end
But now we’ve lost our sort order, so combining the two can be done this way:
def index
qualifiers = {:order => sort_order('created_at')}
if(params[:s])
qualifiers[:conditions] = ['title like ?', "%#{params[:s]}%"]
end
@movies = Movies.all(qualifiers)
end