2011-02-10 67 views
0

我有一個擁有UserProfile類的User類。該電子郵件存儲在用戶表中,因爲他們需要使用它登錄,但是,從我的user_profiles#edit方法中,我希望能夠更新此電子郵件地址。來自相關模型的Rails 3字段驗證

如何在電子郵件字段上進行驗證?

我的類看起來是這樣的(顯然不是正確的,但你的想法):

class UserProfile < ActiveRecord::Base 
    belongs_to :user 

    validates :first_name, :presence => true 
    validates :last_name, :presence => true 
    validates :email, :presence => true, :uniqueness => true, :email_format => true 

    def email=(email) 
    self.user.email = email 
    self.user.save 
    end 
end 

我的表單參數看起來像:

{ 
    "user_profile" => { "first_name" => "John", "email" => "qwerty", .... 
} 

的爲EmailValidator只是取自Railscasts:

class EmailFormatValidator < ActiveModel::EachValidator 
    def validate_each(object, attribute, value) 
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i 
     object.errors[attribute] << (options[:message] || "is not formatted properly") 
    end 
    end 
end 

回答

2

你可以把你的驗證放在用戶模型中。當您在用戶模型上調用保存時,將檢查這些驗證。

而你需要添加以下的關聯:

belongs_to :user, :validate => true, :autosave => true 

,並刪除保存在電子郵件=方法調用,因爲現在的用戶會自動保存。

+0

雖然它不會級聯回UserProfile。該表單仍然表示已成功保存,但調用update_attributes時電子郵件地址並未發生實際變化。 – Dex 2011-02-10 13:07:12