简体   繁体   English

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

[英]More elegant way of doing this 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 am getting each country that has at least one tip. 我得到每个至少有一个小费的国家。 A country has_many tips and a tip belongs_to a country 一个国家有一个很多提示,一个提示属于一个国家

It works. 有用。 But for Ruby it seems a little unelegant. 但对于Ruby来说,它似乎有点不雅。 Is there a better way? 有没有更好的办法?

Thanks in advance 提前致谢

Richard 理查德

@countries_with_tips = Country.joins(:tips).order(:name).uniq
@countries_with_tips = @countries.select{|country| country.tips.present? }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM