ruby-on-rails – before_save不使用Rails 3

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – before_save不使用Rails 3前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个项目模型:
class Project < ActiveRecord::Base
  validates :status,:inclusion => { :in => ['active','closed'] }
  validates :title,:presence => true,:length => { :in => 4..30 }

  before_save :set_default_status_if_not_specified

  private 

  def set_default_status_if_not_specified
    self.status = 'active' if self.status.blank?
  end
end

如果我创建一个这样的新对象:

Project.create!(:title => 'Test 2',:pm_id => 1)

我收到这些错误:验证失败:状态未包含在列表中
但是状态字段应该在保存之前填写.

解决方法

那是因为它在before_save之前验证.

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

(-) save

(-) valid

(1) before_validation

(-) validate

(2) after_validation

(3) before_save

(4) before_create

(-) create

(5) after_create

(6) after_save

(7) after_commit

你可以尝试before_validation吗?

原文链接:https://www.f2er.com/ruby/271047.html

猜你在找的Ruby相关文章