【问题标题】:How make a Model validation on multiple methods?如何对多种方法进行模型验证?
【发布时间】:2015-08-20 16:19:32
【问题描述】:

我想检查:create:update 上的实体属性是否介于0 和5 之间。所以我在我的模型中添加了这样的验证:

class MyObject < ActiveRecord::Base

  attr_accessible :first_attribute, :second_attribute

  validate :check_attributes, on: :create and :update

  private

  def check_attributes
    if self.first_attribute < 0 || self.first_attribute> 5
      errors.add(:first_attribute, "first_attribute must be between 0 and 5")
    end
    if self.second_attribute < 0 || self.second_attribute > 5
      errors.add(:second_attribute , "second_attribute must be between 0 and 5")
    end
  end

end

它适用于创建:当我尝试创建像 MyObject.create!(first_attribute: 7, second_attribute: 4) 这样的实体时,我收到一个错误。如果我输入一个介于 0 和 5 之间的值,它会创建实体。

但是当我更新像my_entity.update_attributes!(first_attribute: 7) 这样的现有实体时,它允许更新,因为它没有进入验证函数。

如何使它适用于两种方法(创建和更新)?

【问题讨论】:

    标签: ruby-on-rails ruby validation model callback


    【解决方案1】:

    该行应该是

    validate :check_attributes, on: [:create, :update]
    

    但您也可以使用内置验证。 :create:update 也是 on 的默认值,所以你也可以省略它:

    validates :first_attribute,
              inclusion: { in: 0..5, message: "must be between 0  and 5" },
    validates :second_attribute,
              inclusion: { in: 0..5, message: "must be between 0  and 5" },
    

    【讨论】:

      【解决方案2】:

      默认情况下,Rails 验证对createupdate 运行。所以应该是:

      validate :check_attributes
      

      请参阅Rails Documentation

      仅当您想验证createupdate 时,才应使用:on 选项。但是,如果您想对两者都进行验证,则无需指定 :on 选项。默认情况下,Rails 将对两者进行验证。

      但是,有更好的方法来验证 0 到 5 之间的属性。您可以使用 Rails inclusion helper 来执行此操作,而不是定义自己的自定义验证器。

      validates :first_attribute,
                inclusion: { in: 0..5, message: "first_attribute  must be between 0 and 5" },
      validates :second_attribute,
                inclusion: { in: 0..5, message: "second_attribute  must be between 0 and 5" }
      

      【讨论】:

        【解决方案3】:

        你试过了吗

        validate :check_attributes, :on => [:create, :update]
        

        这样,验证将仅在创建和更新操作中运行。 这是apidocs的链接。

        【讨论】:

          猜你喜欢
          • 2020-04-06
          • 2015-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-03
          • 2011-01-31
          • 1970-01-01
          • 2011-12-20
          相关资源
          最近更新 更多