2013-02-25 56 views
0

我遇到了一個小問題,我無法解決。我想驗證至少有一個關聯的模型。就像下面驗證軌道中是否存在至少一個關聯對象3.2

class User < ActiveRecord::Base 
has_many :things 
validates_presence_of :things 
end 

class Thing < ActiveRecord::Base 
belongs_to :user 
end 

這時候我通過#update_attributes更新我的優良樣板工程,但是當我簡單地設置@user.things = [],我能夠在數據庫中得到無效數據。我的workaroud解決這個問題是覆蓋設置方法

def things=(val) 
    begin 
    if val.blank? 
     errors.add(:things, "not valid") 
     raise SomeError 
    end 
    super 
    rescue SomeError 
    false 
    end 
end 

但不知何故,這感覺不對。沒有辦法通過驗證和/或回調存檔相同的結果,最好是使返回false(而不是val)並且因此@user.things不會改變(我的意思是緩存@user.things@user.things(true)應該可以正常工作)。

回答

0

您可以創建一個自定義驗證器來檢查事物的存在。取而代之的

validates_presence_of :things

你可以做

validate :user_has_things

def user_has_things 
if self.things.size == 0 
    errors.add("user has no thingies") 
end 
end 
+0

這將是太容易了:)當你調用'#update_attributes它的工作原理(東西:[]) ',但是當你調用'#things ='的時候不會,因爲這不會驗證'User',或者如果你通過'Thinate'中的'validate_associated:user'來驗證'User' g'模型,那麼'user.things'錯過了你正在驗證的東西(即'user.things = [thing,...]'存在於'user.things = []'的驗證中) – jan 2013-02-25 22:10:25

相關問題