Ruby on Rails: an easy way to select all entries of a nested model?

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

Here is the setup:

I have three models that are nested into each other (objects → Tags → Inspections), creating such code for route.rb:

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

I wanted to get all the checks for the object, and here is what my code turned out to be:

 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 it's the best way to do it - I find it cumbersome.

0
source share
2 answers

You can use the has_many :through association. In your models:

 # Facility model has_many :tags has_many :inspections, :through => :tags # Tag model belongs_to :facility has_many :inspections 

And you can get all the checks as follows:

 @inspections = Facility.find(params[:facility_id]).inspections 

But if you have a HABTM relationship between Facility and Tag, it will be more complicated and you will have to write several sql files manually, for example:

 @inspections = Inspection.all(:joins => "INNER JOIN tags ON tags.id = inspections.tag_id INNER JOIN facilities_tags ON tags.id = facilities_tags.tag_id", :conditions => ["facilities_tags.facility_id = ?", params[:facility_id] ) 

Of course, your table structure depends on the code. If you show this, then it would be easier to give the right answer :). Hope this helps!

+3
source
 @facility = Facility.find(params[:facility_id], :include => {:tags => :inspections}) 

Fulfills a single database query (your original solution will use many of them) and returns an object object with all the specified tags and checks. Then you can do something like:

 @inspections = @facility.tags.map(&:inspections).flatten 
0
source

Source: https://habr.com/ru/post/1391128/


All Articles