user3222947
user3222947

Reputation: 197

Rails ActiveRecord model sorting on button click?

I simply want to trigger a simple @foo = Model.sort action on model on a <li><a href="#">Originality</a></li> button click . I don't know how to do just that? Do I have to create a custom route an a new controller and method? Then display instance variable in new view? Or can I use my model controller, index action and somehow display sorting results in same index.html.erb?

Buttons to trigger sorting:

<li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Rankingz <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Originality</a></li>
          <li><a href="#">Dynamics</a></li>
          <li><a href="#">Execution</a></li>
          <li><a href="#">Battle</a></li>
          <li><a href="#">Votes</a></li>
        </ul>
      </li>

Upvotes: 0

Views: 695

Answers (1)

Manoj Monga
Manoj Monga

Reputation: 3083

You can use your index action for the same. Just pass the sorting as params with get request and use them. eg.

In your view

<li class="dropdown">
  <a href="#" class="dropdown-toggle" data-toggle="dropdown">Rankingz <b class="caret"></b></a>
  <ul class="dropdown-menu">
    <!-- We are passing the sort parameter here -->
    <li><a href="?sort=originality">Originality</a></li>
    <li><a href="#">Dynamics</a></li>
    <li><a href="#">Execution</a></li>
    <li><a href="#">Battle</a></li>
    <li><a href="#">Votes</a></li>
  </ul>
</li>

In your index action

 def index
   if params[:sort].present?
    #perform your logic with sort
   end
   #Other logic
 end

Upvotes: 1

Related Questions