2014-06-15 95 views
0

儘管下面的代碼段起作用,但我已經開始探索一種更好的干預方法。任何人都可以更好地瞭解如何構建它?我感謝您的幫助。幹活動記錄模型驗證

class User < ActiveRecord::Base 

    validates :remote_addr, :web_browser, :operating_system, presence: true 

    validates :age_verification, presence: { message: "You must be at least 18 years old to register for this application" } 

    validates :email_address, 
    allow_nil: false, 
    allow_blank: false, 
    presence: { message: "A valid email address is required" }, 
    uniqueness: { 
     case_sensitive: false, 
     message: "This email address has been previously registered" 
    }, 
    email_format: { 
     check_mx: true, 
     mx_message: "This email address has a bad domain", 
     message: "This email address must be formatted properly" 
    } 

end 
+1

麻煩的是,你不重複太多。您可以在AR模型上使用[國際化](http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models)來提取錯誤消息。 'email_address'上需要'allow_blank/nil'嗎? 「存在:真實」還不夠嗎? –

+0

是真的,非常真實。也許我太強調DRY了。我的意思是它仍然可讀。嗯......這可能是矯枉過正。 –

+0

這個問題似乎是脫離主題,因爲它是關於代碼審查 –

回答

0

您可以:

  1. 移動定製消息的I18n文件,更info,例如:

配置/區域設置/ en.yml

en: 
    errors: 
    attributes: 
     age_verification: 
     blank: 'You must be at least 18 years old to register for this application' 
     email_address: 
     blank: 'A valid email address is required' 

    activerecord: 
    errors: 
     messages: 
     invalid_email_address: 'This email address must be formatted properly' 
     email_address_not_routable: 'This email address has a bad domain' 

    activemodel: 
    errors: 
     messages: 
     invalid_email_address: 'This email address must be formatted properly' 
     email_address_not_routable: 'This email address has a bad domain' 

,並加入在場驗證,age_verification,電子郵件字段與其他

2驗證EMAIL_ADDRESS,真的有必要檢查allow_nilallow_blank存在?由於驗證電子郵件格式與它們重疊,即空白和零未被接受爲有效值。對於數據一致性而言,使用數據庫索引和列約束。

所以我是這樣做:

validates_presence_of :remote_addr, :web_browser, 
         :operating_system, :age_verification, :email_address 

    validates :email_address, uniqueness: { case_sensitive: false }, 
          email_format: { check_mx: true } 

舉動錯誤消息en.yml文件(見上文),並添加創建表遷移

change_column <tables>, :email, null: false 
add_index <tables>, :email, unique: true 
+0

我很喜歡這個,但我怎麼會添加一個錯誤消息'email_format'? –

+0

也@Vakiliy這裏是我使用的有效的電子郵件gem :: https://github.com/alexdunae/validates_email_format_of –

+0

:invalid_email_address - 用於無效的電子郵件,:email_address_not_routable - 用於:mx_message,更多信息https://github.com /alexdunae/validates_email_format_of/blob/master/lib/validates_email_format_of.rb#L29 – Vakiliy