2014-01-09 56 views
1

我有一個CompanyArchive模型,它們具有相同的表結構。兩種型號都有validates :name, :uniqueness => true驗證。驗證兩個表中的唯一性

在company.rb文件中,我在設置自定義驗證時出現問題,當我向Company數據庫添加記錄時,它還檢查Archive模型(因此如果具有該名稱的存檔模型中的記錄已經存在那麼它將不會被添加到Company表中)。

我假設這是可行的,但我遇到了麻煩,任何人都可以幫忙嗎?

+0

嘗試添加一個validates_associated:存檔到您的Company.rb – Pavan

+0

您可能想要檢查first_or_create。這可能是有用的http://stackoverflow.com/questions/16644756/first-or-create-by-email-and-then-save-the-nested-model –

回答

5

company.rb

validates :name, uniqueness: true

validate :unique_name

def unique_name 
    self.errors.add(:name, 'is already taken') if Archive.where(name: self.name).exists? 
end 

要記住,雖然這樣的代碼級別唯一約束可以在比賽條件下的並行請求中無法正常工作是非常重要的,除非在某種程度上這可以在數據庫級別完成。

+0

如果你想學習如何避免競爭條件,看到[這個問題](http://stackoverflow.com/questions/34049308/how-to-avoid-a-race-condition-when-validating-uniqueness-across-two-tables-in-ra?lq=1) –