ActiceRecord下的errors

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值