kingjeffrey
kingjeffrey

Reputation: 15270

Ruby on Rails: How to find all items 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. 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?

Upvotes: 2

Views: 2223

Answers (1)

Pete
Pete

Reputation: 18075

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

Upvotes: 4

Related Questions