Ruby on Rails: Simple way to select all records of a nested model?

Posted by Josh Pinter on Stack Overflow See other posts from Stack Overflow or by Josh Pinter
Published on 2010-03-14T06:06:13Z Indexed on 2010/03/14 6:15 UTC
Read the original article Hit count: 253

Filed under:
|
|
|
|

Just curious, I spent an embarrassing amount of time trying to get an array of all the records in a nested model. I just want to make sure there is not a better way.

Here is the setup:

I have three models that are nested under each other (Facilities >> Tags >> Inspections), producing code like this for routes.rb:

map.resources :facilities do |facilities|
  facilities.resources :tags, :has_many => :inspections 
end

I wanted to get all of the inspections for a facility and here is what my code ended up being:

def facility_inspections
  @facility = Facility.find(params[:facility_id])
  @inspections = []
  @facility.tags.each do |tag| 
    tag.inspections.each do |inspection|
      @inspections << inspection
    end
  end
end

It works but is this the best way to do this - I think it's cumbersome.

Thanks in advance.

Josh

© Stack Overflow or respective owner

Related posts about ruby

Related posts about nested