HABTM checking for match of latest 3

Posted by user333614 on Stack Overflow See other posts from Stack Overflow or by user333614
Published on 2010-05-05T15:53:54Z Indexed on 2010/05/05 16:28 UTC
Read the original article Hit count: 201

Here's an interesting one for you folks...

I have a HABTM (has_and_belongs_to_many) relationship between "Dogs" and "Trips". My goal is to find two result sets: 1) Dogs that have been on at least 1 of the last 3 trips and call that @dogs_current 2) Dogs that have NOT been on any of the last 3 trips and call that @dogs_old

I found that I can find what the last 3 trips are by doing this in the Trip model:

  named_scope :last3, :order => 'date DESC', :limit => 3

But not sure how to use that list get 1 and 2. This hack works, but it seems ugly. There must be a better way! :)

@dogs_current = []
@dogs_old = []
@dogs.each do |dog| 
  if (Trip.last3 - dog.trips).size < 3 then
    @dogs_current << dog
  else
    @dogs_old << dog
  end
end

Any ideas? Thanks! -Cam

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about has-and-belongs-to-many