2014-01-27 119 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開始工作。