Testing value of each related model
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?)
精彩评论