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
Rails模型验证与自定义错误
本文探讨了Rails中如何为Article和Comment模型设置验证规则,包括必填字段检查及关联文章是否已发布等。同时介绍了如何使用errors.add方法添加自定义错误消息。

被折叠的 条评论
为什么被折叠?



