views:

162

answers:

1

Suppose I have three models: Student, SchoolClass, and DayOfWeek. There is a HABTM relationship between Student and SchoolClass, and between SchoolClass and DayOfWeek. What I'd like to do is find all school classes belonging to a given student that meet on Monday.

Now I suppose I could do something like:

@student = Student.find(:student_id)
@student_classes = @student.school_classes.find(:all)
@student_classes_on_monday = Array.new
@student_classes.each do |student_class|
  if student_class.day_of_week.include?("Monday")
    @student_classes_on_monday << student_class 
  end
end

Is there a way to accomplish lines 2-8 in a single find method?

+2  A: 

Looks like you want to use select:

@student_classes_on_monday = @student_classes.select do |student_class|
  student_class.day_of_the_week.include? "Monday"
end

Select will return all the elements for which the block is true. So you can just pass your condition as the block and get back the items that meet the criteria.

You could also use the 'like' keyword to try to match this in your database query. I'm not positive what your schema is like, but something like this could get you started:

@student.school_classes.find(:all, :conditions => ['day_of_week LIKE ?', '%Monday%'])

I'm a bit rusty on the syntax for this myself, so I'm pulling this example from here (and hence won't guarantee it is totally correct): http://railsruby.blogspot.com/2006/08/like-as-condition-to-get-records.html

Pete
That is more elegant, but what I'd really like is a find_all_by method that returns just the sought classes. I'll update my question to be specific to this point.
kingjeffrey
tried to give a little insight into a find query which might do what you want. not sure if it is exactly what you need though.
Pete
Thank you Pete. If your second bit doesn't work for me, the first will.
kingjeffrey