12月6日 看Active Record validation ; 做jdstore ,注意gem bootstrap 版本只支持bootstrap3。

Active Record validation:

 new_record?()//用于验证刚新建,但没存入database中的数据 ,返回true或false

 persisted?() //和new_record/()正相反,从英文意看出,Returns true if the record is persisted.it's not a new record and it was not destroyed.

 


  • create //验证失败仅仅不会执行代码,返回false.
  • create! //带!号的话,验证失败会弹出💥信息。
  • save //save(validate: false)带上这个参数,会跳过验证
  • save!
  • update
  • update!     // update_all 等一些method会跳过验证
Active Record 执行验证后,所有发现的错误都可以通过实例方法 errors.messages 获取。

例子: p.errors.messages =>{错误的信息} 

 


 

 

 数据验证辅助方法:

所以辅助方法都可以用 :on(当用什么action时验证)  and  :message(自定义返回的错误消息) 

1.acceptance:这个方法检查表单提交时,用户界面中的复选框是否被选中。这个功能一般用来要求用户接受应用的服务条款、确保用户阅读了一些文本,等等。详细见https://ruby-china.github.io/rails-guides/active_record_validations.html#displaying-validation-errors-in-views

2 validates_asscoiated: 这个方法用在任意关联的model,放置在has_many后。

例子:

 

class Library < ApplicationRecord
  has_many :books
  validates_associated :books
end

 3 confirmation ,用于检查两个文本字段的值是否完全相同,如确认密码。需要在model和view中写。见下:

https://ruby-china.github.io/rails-guides/active_record_validations.html#displaying-validation-errors-in-views

 4 length: {}  //限定长度。

5  numericality 限定只为数字和数字范围。

6. presence 和 absence 可以验证属性值,也可以验证关联对象是否存在。

7. uniquencess :true 创建唯一的属性。 


条件验

可以使用if 和 unless.

class Order < ApplicationRecord
  validates :card_number, presence: true, if: :paid_with_card?
 
  def paid_with_card?
    payment_type == "card"
  end
end

另外,一个条件内可以有多个验证,用到with_option 

class User < ApplicationRecord
  with_options if: :is_admin? do |admin|
    admin.validates :password, length: { minimum: 10 }
    admin.validates :email, presence: true
  end
end

 

posted @ 2017-12-06 10:09  Mr-chen  阅读(185)  评论(0编辑  收藏  举报