leonel
leonel

Reputation: 10224

Rails 3. How to exclude records from grouped_collection_select?

I have a form to record payments for instructors. The payments are recorded in the expenses table. I have the following working fine:

<%= f.grouped_collection_select :scheduled_session_id, User.where(:role => 'instructor'), :scheduled_sessions, :full_name, :id, :identifier_with_cost, :include_blank => true %>

It displays a select menu with instructor names and their assigned sessions. For example...

Peter Parker
  Biology    $350 April 27
  Chemistry  $400 April 28
Professor X
  Genetics   $400 April 27
  History    $350 April 28
  Literature $350 April 29

But I want to exclude the sessions that have already been paid. The scheduled_sessions table has a Boolean column called "paid".

I can make that query with ScheduledSession.where(paid: [false, nil]) but how to I implement it on grouped_collection_select?

Upvotes: 1

Views: 601

Answers (1)

leonel
leonel

Reputation: 10224

After looking more closely at the documentation, (you know how after a while of coding the brain can't process much information, that's why I'm implementing the pomodoro technique this week): grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) public, it's a group_method what provides the list of child records.

So to come up with this solution I ignore the Expense model for a little while. I just care about the User and ScheduledSession model for now, because that's what going to generate my select menu. I created a method in the parent model:

class User < ActiveRecord::Base
has_many :scheduled_sessions, :foreign_key => 'instructor_id'

def not_paid_scheduled_sessions
   ScheduledSession.where(:instructor_id => self.id).where(paid: [false, nil])
 end

So instead of...

f.grouped_collection_select :scheduled_session_id, User.where(:role => 'instructor'), :scheduled_sessions, :full_name, :id, :identifier_with_cost, :include_blank => true

I use...

f.grouped_collection_select :scheduled_session_id, User.where(:role => 'instructor'), :not_paid_scheduled_sessions, :full_name, :id, :identifier_with_cost 

Hope it helps someone else too.

Upvotes: 2

Related Questions