How to set default condition with field name in ransack?

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

+4
source share
1 answer

I am not 100% sure that I have this question and it is a bit old, but I will try anyway:

So, you have a model that you want to find, and you have a condition that you always want to apply. Now the first thing that comes to my mind is just your condition for the result in your controller, for example:

 @q = Forum(params[:q]) @forums = @q.result.where("role_id = ?", 1) # the number of course should be the id of the moderator object 

Or you can try a hidden field in your search form:

 <%= f.select(:role_name_matches, Role.pluck(:name), :as => :hidden, :input_html => { :value => "moderator" } ) %> 

If you mean something else and still need it, please explain to me what you mean. I have quite some experience with ransack and would like to help.

0
source

All Articles