user3752786
user3752786

Reputation: 75

Stacking each on each on each in Ruby

I'm iterating through some ActiveRecord models like this:

(For example sake let's say that you can't directly get all animal genres. It's iterating related question, not association stuff):

Animal.all.each do |animal|
    animal.families.each do |family|
        family.genres.each do |genre|
            genre.gsub("o","a")
            genre.save!
        end
    end
end

I don't think its the best way to do it. Is there any solution for making it better? Like one iterator that will do .each on each model?

Upvotes: 2

Views: 52

Answers (2)

Mark Swardstrom
Mark Swardstrom

Reputation: 18070

One way that will speed this up, is try to do all the queries first.

animals = Animal.includes(families: genres)
animals.each do |animal|
  animal.families.each do |family|
    family.genres.each do |genre|
      genre.gsub("o","a")
      genre.save!
    end
  end
end

Upvotes: 3

Uri Agassi
Uri Agassi

Reputation: 37409

How about using flat_map:

Animal.all.flat_map(&:families).flat_map(&:genres).each do |genre|
  genre.gsub("o","a")
  genre.save!
end

(this of course totally ignores any ActiveRecord related solutions, which will be better)

Upvotes: 2

Related Questions