A More Elegant Way to Do It in Rails

I have the following code:

@countries = Country.find( :all, :order => 'name' ) @countries_with_tips = [] @countries.each do |country| if country.tips.any? @countries_with_tips.push( country ) end end 

I get every country that has at least one piece of advice. The country has some tips and tricks for the country.

It works. But for Ruby, this looks a little unbalanced. Is there a better way?

Thank you in advance

Richard

+4
source share
2 answers
 @countries_with_tips = Country.joins(:tips).order(:name).uniq 
+5
source
 @countries_with_tips = @countries.select{|country| country.tips.present? } 
0
source

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


All Articles