2015-06-24 53 views
1

我有窗體,批量創建一些對象。對於我的流量,我不得不一次保存它們,或者根本不保存。問題是 - 當我進行驗證時,它們並不失敗,因爲每個對象都根據db中的當前記錄進行驗證(我有唯一性驗證),但是我還需要驗證當前對象是否存在於每個未保存的對象中。小例子驗證幾個未保存的對象

class User 
    #field: email 
end 

在我的表單對象中,我有一個用戶數組。並在循環我做

@users.each do |user| 
    valid_users << user if user.valid? #and this is where i need to validate `user` within not just DB, but within @users aswell 
end 

我如何實現這一目標?

回答

1

首先,您需要檢查所有未保存的對象通過驗證測試或沒有,如果是,要做到這一點,你可以代替的獨特領域email

if @users.map { |user| user.email.downcase }.uniq.length == @users.size 
    @users.each do |user| 
    valid_users << user if user.valid? 
    end 
else 
    # Error: Emails of the users must be unique 
end 

希望這有助於做到這一點!要做到這一點

1

您可以將它們包裝在一個事務中,如果發生故障,它將回滾整個批處理。

begin 
    ActiveRecord::Base.transaction do 
    @users.map(&:save!) 
    end 
rescue ActiveRecord::RecordInvalid 
end 
1

爲什麼不只是檢查user.valid?驗證數據庫記錄,然後手動檢查@users,僅在不重複時才保存。

@users.each do |user| 

    #the following would check for identical objects in @users, but that may not be what you want 
    valid_users << user if user.valid? and @users.count(user)<2 

    #this would check only the required field on the array 
    valid_users << user if user.valid? and @users.map(&:email).count(user.email)<2 

end 
0

的一種方式,可以使用all?

if @users.all?{|u| u.valid? } # true, only when all users are validated 
    # save all users 
else 
    # redirect/render with error message. 
end 
+0

這不會檢查是否有不上,保存收藏,例如,在範圍內的任何衝突2位用戶使用相同的電子郵件地址 – Avdept

+0

@Avdept:嗯,在問題的任何地方都沒有提到。 – Surya