views:

25

answers:

3

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 itself.

A: 

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.

marcgg
Thanks! I also like the 'detect' one, gives some indication of what i'm trying to accomplish.
Novapax
A: 

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

if @author.articles.count == @author.articles.count(:conditions => { :published => true })
 puts "..."
end
gregor
That would be even easier. But in my case its not a DB-field, but a custom generated attribute.
Novapax
A: 

I think there is yet another one:

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

Fer