Ruby on Rails: how to find all elements with a hash that contain a specific value
Suppose I have three models: Student
, SchoolClass
and DayOfWeek
. There is a HABTM relationship between Student
and SchoolClass
, and between SchoolClass
and DayOfWeek
. I would like to find all of the classes that this student owns 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 search method?
a source to share
It 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 elements for which the block is true. This way you can just pass your condition as a block and return items that match the criteria.
You can also use the 'like' keyword to try and match this in your database query. I'm not sure what your schema is, but something like this might get you started:
@student.school_classes.find(:all, :conditions => ['day_of_week LIKE ?', '%Monday%'])
I'm a little rusty on the syntax for this myself, so I'm pulling this example from here (and therefore doesn't guarantee it's absolutely correct): http://railsruby.blogspot.com/2006/08/like-as-condition- to-get-records.html
a source to share