开发者

Testing value of each related model

开发者 https://www.devze.com 2022-12-26 18:04 出处:网络
Does Ruby (or Rails) provide an easy way to accomplish the following: if @author.articles.each(:published == true)

Does Ruby (or Rails) provide an easy way to accomplish the following:

if @author.articles.each(:published == true)
  puts "all articles of this author are published"
end

I think the example speaks for itsel开发者_JAVA百科f.


Maybe someone will find something better, but here are some things that would work:

unless @author.articles.map{|a| a.published == true}.include?(false)
  puts "all articles of this author are published"
end

or...

if @author.articles.select{|a| !a.published}.size == 0
  puts "all articles of this author are published"
end

or...

if @author.articles.detect{|a| !a.published}.nil?
  puts "all articles of this author are published"
end

My preference goes for the last one.


Or if you don't have to load the articles ...

if @author.articles.count == @author.articles.count(:conditions => { :published => true })
 puts "..."
end


I think there is yet another one:

puts "all #{@author.name}'s articles are published" if @author.articles.all?(&:published?)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号