Howto set a default condition with fieldname? #103

tonymarschall opened this Issue Jun 7, 2012 · 3 comments


None yet
2 participants

I have a user and a roles model, both are associated via habtm. In the search form i want to filter by users who have a specificr role (by name: moderator).

Source looks like this:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles, :join_table => :users_roles

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 @user, :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 the field name or how can i search with a preset condition ( == :moderator)?

It seesm like i have to use a 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|

<%= search_form_for @q, :builder => SimpleForm::FormBuilder do |f| %>

    <%= f.input :moderator_users_in, :wrapper => :inline,
                                     :collection => User.joins(:roles).where(:roles => {:name => :moderator}),

With the 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 to 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)

@tonymarschall tonymarschall reopened this Jun 12, 2012


jonatack commented Sep 5, 2014

This is more than 2 years old and more of a "how to" question than a bug report. Closing.

@jonatack jonatack closed this Sep 5, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment