好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

rails跳过验证

rails跳过验证

2010 - 12 - 21

rails validation 文章分类: Ruby编程

rails3中的验证,以下方法会触发验证

Java代码

create   create!   save   save!   update   update_attributes   update_attributes!  


以下方法则会跳过验证,将数据保存到数据库中

Java代码

decrement!   decrement_counter   increment!   increment_counter   toggle!   update_all   update_attribute   update_counters  


当使用

Java代码

save(:validate =>  false )  


验证也会被跳过。

Java代码

validates_acceptance_of  

必须接受(多用于霸王条款)

Java代码

class  Library < ActiveRecord::Base      has_many :books     validates_associated :books   end   




Java代码

validates_confirmation_of :password(多用于验证两次密码)  



Java代码

class  Account < ActiveRecord::Base   validates_exclusion_of :subdomain, :in => %w(www),     :message =>  "Subdomain %{value} is reserved."    end (用于验证是否包含此www)  



Java代码

class  Product < ActiveRecord::Base   validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/,     :message =>  "Only letters allowed" end    (格式验证)  



上传时验证文件类型:

15 thanks

Only attr_accessible attributes will be updated

If your model specified  attr_accessible  attributes, only those  attributes  will be updated.

Use  attr_accessible  to prevent mass assignment (by users) of  attributes  that should not be editable by a user. Mass assignment is used in  create  and  update  methods of your standard controller.

For a normal user account, for example, you only want  login  and  password  to be editable by a user. It should not be possible to change the  status  attribute through mass assignment.

   class    User    <    ActiveRecord   ::   Base  
      attr_accessible    :login  ,   :password 
   end 

So, doing the following will merrily return true, but will not  update  the status attribute.

   @user  .   update_attributes   (  :status   =>   '  active  ') 

If you want to  update  the  status  attribute, you should assign it separately.

   @user  .  status   =   '  active  ' 
    save  

4 thanks

Calls attribute setter for each key/value in the hash

This is a convenience to set multiple  attributes  at the same time. It calls the "setter" method

   self  .  attribute  =(  value  ) 

3 thanks

Skipping validation

Unlike the  save  method, you can’t pass false to  update_attributes  to tell it to skip validation. Should you wish to do this (consider carefully if this is wise)  update  the  attributes  explicitly then call  save  and pass false:

   @model_name  .   attributes    =   params  [  :model_name  ] 
   @model_name  .   save    false 

查看更多关于rails跳过验证的详细内容...

  阅读:44次

上一篇: 关于partial的使用

下一篇:ssh技巧