Niels
Niels

Reputation: 609

Access id active record in instance method

I'm having some problems accessing the ID attribute of an ActiveRecord model. I want to write a method similar to this:

class Category < ActiveRecord::Base
  def has_articles?
    return true if !Article.find_by_category_id(id).empty?

    return false
  end
end

But I can't access the ID of the instance. When I add attr_accessor :id to the class, I have a lot of test failing saying they can't access category.id.

Upvotes: 0

Views: 721

Answers (1)

tokland
tokland

Reputation: 67860

You should write something like this:

class Category < ActiveRecord::Base
  has_many :articles

  def has_articles?
    articles.present? # or !articles.empty? or articles.count > 0 or articles.any?
  end
end

Upvotes: 3

Related Questions