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?
Looks like you want to use select:
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:
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