在Rails中这样做更优雅的方式

时间:2012-10-13 14:43:55

标签: ruby-on-rails ruby

我有以下代码:

@countries = Country.find( :all, :order => 'name' )

@countries_with_tips = []

@countries.each do |country|
  if country.tips.any?
    @countries_with_tips.push( country )
  end
end

我得到的每个国家至少有一个小费。一个国家/地区有一些提示,一个提示属于一个国家/地区

有效。但对于Ruby来说,它似乎有点不雅。还有更好的方法吗?

提前致谢

理查德

2 个答案:

答案 0 :(得分:5)

@countries_with_tips = Country.joins(:tips).order(:name).uniq

答案 1 :(得分:0)

@countries_with_tips = @countries.select{|country| country.tips.present? }