我有一个用户和一个角色模型,两者都通过 habtm 关联,并且有一个与角色关联的论坛模型。在论坛的搜索表单中,我想按具有特定角色的用户(按名称:版主)进行过滤。
源代码如下所示:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles, :join_table => :users_roles
rolify
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource, :polymorphic => true
class Forum < ActiveRecord::Base
has_many :roles, :as => :resource
...
<%= simple_form_for @forums, :html => { :class => 'form-horizontal' } do |f| %>
...
<%= f.input :roles_users_id_in,
:collection => User.joins(:roles)
.where(:roles => {:name => :moderator}) %>
是否可以将其组合到字段名称中,我是否需要使用自定义设置进行设置,或者如何使用预设条件(role.name == :moderator)进行搜索?
更新
看起来我必须使用自定义的ransacker,我想出了以下内容:
class Forum < ActiveRecord::Base
..
ransacker :moderator_users, :formatter => proc { |v|
Role.joins(:users).where(:roles => { :name => :moderator,
:resource_type => :forum},
:users => {:id => v}).map(&:resource_id)
} do |parent|
parent.table[:id]
end
<%= search_form_for @q, :builder => SimpleForm::FormBuilder do |f| %>
<%= f.input :moderator_users_in,
:collection => User.joins(:roles)
.where(:roles => {:name => :moderator}),
...
使用上面的解决方法,有一个论坛 sql 查询和一个针对每个用户的查询。是否可以将其结合起来并将 sql 查询设置为如下所示:
SELECT DISTINCT `forums`.* FROM `forums`
LEFT OUTER JOIN `roles` ON `roles`.`resource_id` = `forums`.`id` AND
`roles`.`resource_type` = 'Forum'
LEFT OUTER JOIN `users_roles` ON `users_roles`.`role_id` = `roles`.`id`
LEFT OUTER JOIN `users` ON `users`.`id` = `users_roles`.`user_id`
WHERE `roles`.`name` = 'responsible' AND `users`.`id` IN (1,3,6)