2014-06-15 65 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