【发布时间】:2016-04-05 05:11:51
【问题描述】:
我用过 Ransack Gem,Rails 4。
roles_controllers.rb
def index
@q = Role.ransack(params[:q])
@roles = @q.result(distinct: true)
end
这是模型(role.rb)中的实例方法
def user_count
self.users.count
end
这是我的 html 表头(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>
用户和角色之间存在关系,一个角色有_许多用户。
在这里,我想按 asc 和 desc 顺序对这些用户数进行排序,但是使用此代码它不起作用。
如果可以,请帮助我。
谢谢
【问题讨论】:
-
你也可以从角色控制器中粘贴索引方法的代码吗?
-
这里我上传了控制器和视图的代码。如果有,请检查并告诉我解决方案。
-
@Surya:你有问题的答案吗?
-
试试这个:github.com/activerecord-hackery/ransack/wiki/… 我怀疑你的角色中有 user_id 列,那么你可能需要相应地更改 ransack 的查询。尝试在角色表中为用户设置计数器缓存,然后使用 users_count 进行排序,如链接中所述。
-
@Surya : users 表中有 role_id。您给定的链接与我所要求的不同。首先了解我的问题,然后给出答案。
标签: ruby ruby-on-rails-4 sqlite ransack