I have a user and role model, both connected via habtm, and there is a forum model associated with roles. In the ransack search form for forums, I want to filter users who have a specific role (by name: moderator).
The source is as follows:
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}) %>
Is it possible to combine this into a field name, do I need to configure something with a custom rating, or how can I perform a search with a given condition (role.name ==: moderator)?
Update
He sees how I should use custom ransacker, and I came up with the following:
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}), ...
With a workaround above, there is a forum SQL query and a query for each user. Is it possible to combine this and set the sql query something like this:
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)
See also: https://github.com/ernie/ransack/issues/103