2011-05-24 64 views
0

我正在寻找实现自定义验证的最佳方式。我知道这一点:最好的rails方式来实现自定义验证?

validates :email, :uniqueness => {:scope => :user_id} 

它的作品完美。但是,我想这样做(虚构的情况下,但它很好地说明):

validates :email, :uniqueness => {:scope => 'user.name'} 

我想利用海关验证像解释here on rails cast,但似乎有点矫枉过正使用模块这一点。

有人吗?

+0

只是一个好奇心,但你想用这个验证什么?你的方法和验证之间有什么区别:email,:uniqueness => true? – bruno077 2011-05-24 18:12:37

回答

3

使用验证方法。

class Model 

    validate :validate_email_with_scope 

    private 

    def validate_email_with_scope 
     if Model.where(...).any? 
     errors.add(:email, 'is not unique') 
     end 
    end 

end 

Model.where(...).any?替换为您的查询。

+0

工程很棒。你如何告诉活动记录从当前请求中排除当前对象ID? – Hartator 2011-05-25 09:08:29

+0

'where('foo =?AND id <>?','bar',id)' – 2011-05-25 12:51:02