Search code examples
ruby-on-railsassociationssimple-form

how to filter association with grouped select in Rails


Team has_many :users
User belongs_to :team

I can also scope my users:

scope :active, -> (active) {where active: active }

In my form, I want a select of active users grouped by teams.

<%= f.association :user, collection: Team.all, as: :grouped_select, group_method: :users %>

gives me a grouped select of users (both active and non active) by teams.

<%= f.association :user, collection: User.where(active: true) %>

gives me a select of active users.

I can't figure out the syntax to combine the two. Thanks !


Solution

  • I've added a method in my user.rb :

    def self.for_select
      Team.active.map do |team|
        [team.name, team.users.active(true).map { |u| [u.name, u.id] } ]
      end
    end
    

    and used a grouped_option_for_select in my form :

    <%= f.select :user_id, grouped_options_for_select(User.for_select) %>
    

    This blog post was very helpful : http://andrewradev.com/2011/05/25/grouped-select-helper-methods-in-rails/

    Anyone has a better way ?