0

I've two models

  class Article < ActiveRecord::Base
    has_one :review
  end

  class Review < ActiveRecord::Base
    belongs_to :article
  end

Now I would like to have this method in Article

  class Article < ActiveRecord::Base
    has_one :review

    def self.has_review?

    end

  end

I've tried with .count, .size....but I've errors...how can I do to have the following code working

@article = Article.find(xxx)
if @article.has_revew?
 ....
else
 ...
end

The reason why I need it is becaus I will have different action in views or controller, if there is one Review or none

Regards

1 Answers1

0
class Article < ActiveRecord::Base
  has_one :review

  def has_review?
    !!review
  end
end

This just defines a method on the instance (def self.method defines a class method). The method tries to load review. If the review does not exist, it will be nil. !! just inverts it twice, returning true if a review exists or false if the review is nil.

iblue
  • 29,609
  • 19
  • 89
  • 128
  • Thanks...last option, if the Review has a scope and I would like to check with the scope for example scope :active, {:conditions => {:approved => true}} – user200302 Aug 03 '12 at 07:48