Question

I'm very new to Rails, Databases, and web development in general, right now my feature is working but I'm 100% sure it's not the cleanest or most Ruby-esq way of doing it. Basically I want to use two separate links that sort the same table by different columns, without using two controller actions and two views. I'd rather just user the one index action that takes a parameter indicating how to sort the returned data.

Current Controller:

Controller

def index
  @casinos = Casino.order('name ASC')
end

def casinos_by_region
  @casinos = Casino.order('location ASC')
end

And links in the view

 %h3 Sort by:
 = link_to 'Name', casinos_path
 %br
 = link_to 'Location', casinos_by_region_path

I read the docs but I didn't see an obvious way on passing an argument from the view to controller using a link_to path? I know I could do it other ways, but I refuse to believe I can't do it this way. Sorry for the dumb question!

Was it helpful?

Solution 2

How about this:

def index
  @casinos = Casino.order("#{params[:sort_param]} ASC")
end


%h3 Sort by:
= link_to 'Name', casinos_path(:sort_param => "name")
%br
= link_to 'Location', casinos_path(:sort_param => "location")

The path in link_to can take a hash which are parameters on the request. You can set a parameter (in this case sort_param) with what value you want to sort by, then use that in your order on the index method of the controller.

OTHER TIPS

Thumbs up to CDub. Just to enhance it, you might want to add a little safety to the sorting by assuring the params[:sort_param] contains an expected value in case someone decides to key in the url. The code below not only assures you've got an acceptable sorting key but also provides a default value for the first visit to the url.

def index
  params[:sort_param] = %w{name location}.include?(params[:sort_param]) ? params[:sort_param] : 'name'
  @casinos = Casino.order "#{params[:sort_param]} ASC"
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top