How to use sort_link with model instance method in rails 4 with Ransack Gem?

I used Ransack Gem, Rails 4.

roles_controllers.rb

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

This is the 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 a relationship between the user and the role. One role has several users.

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

Help me if you can.

thanks

+4
source share
1 answer

Ransack is very smart, try changing the line

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

to

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

: @q Ransack Role, sort_link @q, users_count " ".

-2

Source: https://habr.com/ru/post/1622316/


All Articles