class Article < ActiveRecord::Base
validates :title, :presence => true
validates :body, :presence => true
belongs_to :user
has_and_belongs_to_many :categories
has_many :comments
scope :published, where("articles.published_at IS NOT NULL")
scope :draft, where("articles.published_at IS NULL")
scope :recent, lambda { published.where("articles.published_at > ?",
1.week.ago.to_date)}
scope :where_title, lambda { |term| where("articles.title LIKE ?", "%#{term}%") }
def long_title
"#{title} - #{published_at}"
end
def published?
published_at.present?
end
end
class Comment < ActiveRecord::Base
belongs_to :article
def article_should_be_published
errors.add(:article_id, "is not published yet") if article && !article.published?
end
end
This gets you a step closer to your goal. When building validations, Active Record gives you nice
objects called errors to use. Whenever you want to add a validation error to the list of errors, you just say
errors.add(column_name, error_message). So, let’s implement a method called