2014-01-27 121 views
0

我想在rails中编写自定义验证以检查我输入的值是否在数据库中有重复。Rails自定义验证

我需要核对基于关闭4个不同的表/模型

我想写这样的用于验证的值:

class Locations::BranchBusinessGroup < Locations::Database 

validate :url_duplicated 

private 
    def url_duplicated 
    if self.location.url_prefix.valid? 
     errors.add(:location, 'URL is take') 
    else 
     if self.custom_url.valid? && self.self.business_group.is_on_web #both in different models 
     errors.add(:location, 'URL is used in a custom URL') 
     end 
    end 
end 

url_prefixurl_suffix,“:CUSTOM_URL ',is_on_the_web是由表单输入的所有字段。逻辑应该检查url_prefixurl_suffix是否已经输入,如果它们没有匹配':custom_url'和is_on_the_web

这是不正确的编码方式和它的超级错误。它只是我想如何检查验证的想法。任何灯光都会很好。

错误我得到的是:

undefined method有效“?对于“尚蒂伊-VA”:String`

+0

问题是? – rlecaro2

+0

已修改。想知道我该如何编写这样的自定义验证。 –

+0

您使用的是什么ORM,ActiveRecord?什么是父'Locations :: Database'类?另外,请澄清一下会使这条记录无效的逻辑。从你的例子中,我们不清楚'url_suffix','custom_url'和'is_on_web'应该代表什么。 – PinnyM

回答

0

目前还不清楚我到底是什么LocationBusinessGroup是,但总的想法是这样的:

def url_duplicated 
    if self.class.where(url_prefix: url_prefix).where.not(id: id).exists? 
    errors.add(:location, 'URL is taken') 
    elsif self.class.where(custom_url: custom_url, is_on_web: true).where.not(id: id).exists? 
    errors.add(:location, 'URL is used in a custom URL') 
    end 
end 

本质上讲,你希望做一个查找到查找是否存在符合这些条款的记录(并且没有记录本身的id)。请注意,where.not(...)语法只能从Rails 4开始工作。