I have a rails app that handles a lot of information about a set of experimental plates. Along with holding information about each plate, I have another table locations, that’s nested with the plates, as in plates has_many locations and locations belongs_to plates. The locations is a separate table because these plates can get shipped to different locations a lot. This is a way for us to track where all the plates are. Most importantly, we want to know which location for a give plate has the latest date, because this will tell us where the plate currently is.

For the most part, there are only a limited number of places where the plate will be. We have a list in the model. On our main page, I wanted to have a link to each of the main places showing which plates are at that location. Here’s how I did it:

In my controller

def plates_at_uc
    @all = Plate.by_serial_number
    @title = 'UC'
    @plates = Enumerator.new do |y|    
      @all.map do |plate|
          if (plate.locations.current_location.last.location == 'UC')
            y << plate
    render action: "plates_by_location"

I have a method for each of the locations where the plates could be. The important bit here is the enumerator that I set up. This sets up the instance variable with all the plates that I’m going to display in the view. I have to go through each plate and find its present location. If that location equals the one I want (in this case UC), I add the plate to my enumerator. I set up @title so that I can use the same view for the results and display the location in the title of the page.