Reputation: 609
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
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