4

I have used Ransack Gem,Rails 4.

roles_controllers.rb

def index
  @q = Role.ransack(params[:q])
  @roles = @q.result(distinct: true)
end

This is instance method in model(role.rb)

  def user_count
    self.users.count
  end

This is my html table header(Roles/index.html.erb)

    <table class="table table-bordered table-framed rb-usr-tbl">
    <thead>
    <tr>
      <th><%= sort_link(@q, :name) %></th>
      <th>Description</th>
      <th><%= sort_link(@q,:role_users_user_count) %></th>
      <th colspan="2">Actions</th>
    </tr>
    </thead>

    <tbody class="role-index">
     <% @roles.each do |role| %>
        <tr>
          <td><%= role.human_role %></td>
          <td><%= role.description %></td>
          <td><%= role.user_count %></td>

          <td>
            <%= link_to edit_role_path(role), :remote => true,:title => "Edit Role" do %>
                <i class="icon-pencil7 rb-pencil"></i>
            <% end %>
          </td>
          <td>
            <%= link_to role, method: :delete,:title => "Delete Role", data: { confirm: 'Are you sure?' } do %>
                <i class="icon-trash rb-trash"></i>
            <% end %>
          </td>

        </tr>
    <% end %>
    </tbody>
  </table>

There is relationship between user and role are One role has_many users.

Here i want to sort this count of users in asc and desc order but with this code it does not work.

Help me if you can.

Thanks

Jigar Bhatt
  • 4,217
  • 2
  • 34
  • 42
  • Can you also paste the code of your index method from roles controller? – Surya Dec 31 '15 at 08:36
  • Here i have uploaded code of controller and view. please check and let me know solution if you have. – Jigar Bhatt Dec 31 '15 at 09:05
  • @Surya : Do you have the answer of the question? – Jigar Bhatt Jan 02 '16 at 06:17
  • Try this: https://github.com/activerecord-hackery/ransack/wiki/Sorting-in-the-Controller I am suspecting that you have user_id column in roles, then you might have to change the query of ransack accordingly. Try setting a counter cache in roles table for users then use users_count for sorting as mentioned in link. – Surya Jan 02 '16 at 11:35
  • @Surya : There is role_id in users table. Your given link is different than what i am asking.First Understand my question then gives answer plz. – Jigar Bhatt Jan 02 '16 at 11:58
  • i found this article but in desc order http://stackoverflow.com/questions/2642182/sorting-an-array-in-descending-order-in-ruby – youngdero Jan 07 '16 at 14:05
  • @youngdero : this link is not helpful for my question. – Jigar Bhatt Jan 08 '16 at 06:01

1 Answers1

-2

Ransack is very smart itself, try to change line

<th><%= sort_link(@q,:role_users_user_count) %></th>

to

<th><%= sort_link(@q, :users_count) %></th>

Explanation: In the variable @q you keep a Ransack query object on the model Role, if you call sort_link on @q it will apply users_count as "join users relation and order by users count".

Semjon
  • 983
  • 6
  • 17