2012-11-21 241 views
0

我有跟隨着的http://ruby.railstutorial.org/Rails的驗證領域

class User < ActiveRecord 
    attr_accessible ..., :password, :password_confirmation 
    has_secure_password 

    validates :password, :presence => true, 
         :length => { :minimum => 6 } 
    validates :password_confirmation, :presence => true 

    .... 
end 

問題是要創造能正常工作的新用戶,這兩個密碼必須存在,他們需要匹配,當我更新要求我提供密碼

例如,如果另一個控制器想要更改任何字段的用戶,我必須提供密碼,否則我將無法更新。

如何在創建模型或進行密碼更新時制定一個只需要password/password_confirmation的連接?

+0

請勿在編輯表單上顯示密碼和密碼確認字段。 – MurifoX

+0

我想改變字段沒有編輯表格另一個控制器,例如在控制檯中的問題 USER1 = User.first user1.field1 =「喜」 user1.save 這將留下一個錯誤的密碼/ password_confirmation不能爲空 – fxe

回答

1

如果您使用的是rails3,您可以skip validations。從文檔:

以下方法跳過驗證,並將數據庫保存到 而不管其有效性。他們應該與 謹慎使用。

  • 遞減!
  • decrement_counter
  • 增量!
  • increment_counter
  • toggle!
  • 觸摸
  • update_all
  • update_attribute
  • update_column
  • update_counters

注意保存也有如果通過:validate => false作爲參數跳過驗證的能力。應謹慎使用此技術。

基本上,使用find找到合適的用戶,更新你想要的任何領域,user.save!(:validate=>false)和鮑勃是你的叔叔!

+0

爲什麼你想跳過用戶輸入驗證?這是否不符合開始驗證的目的? –

+0

@ChrisPeters如果像OP一樣更新模型並且不想打擾驗證,則可以跳過驗證。 – hd1

+0

「不用打擾驗證」是懶惰的出路,可能會導致數據完整性問題。如果用戶決定將必填字段留空,該怎麼辦?它們會生成無效數據或導致SQL錯誤,具體取決於是否在基礎列上放置了NOT NULL約束。 –

1

Rails支持條件驗證,例如,在您的用戶模型

validates :password_confirmation, :presence => true, :if => :new_password 

def new_password 
    current_user and current_user.changing_password? 
end 

您需要在new_password方法如何分辨什麼條件都滿足時,要驗證弄清楚。

請參閱:http://railscasts.com/episodes/41-conditional-validations