2014-01-16 29 views
0

我使用Google場所API來收集配置文件中的任意數量的位置。每個位置都有profile_id,4個地址字段以及lat和long。我想確保每個配置文件的所有位置都是唯一的。has_many驗證在rails中的獨特子項4

目前,我正在使用下面的代碼來驗證4個地址字段的唯一性,這是完美的工作,但這會導致驗證錯誤返回到視圖。我寧願保存配置文件和位置(刪除重複項)而不向用戶返回錯誤。

這樣做的最好方法是什麼?有沒有rails方法,或者我應該創建自己的驗證前功能?

class Profile < ActiveRecord::Base 
    has_many :locations 

    accepts_nested_attributes_for :locations, allow_destroy: true 

     etc etc 

end 

class Location < ActiveRecord::Base 

    belongs_to :profile 

    # Only allow unique locations for each profile 
    validates_uniqueness_of :profile_id, scope: [:sublocality, :locality, :administrative_area_level_1, :country] 

     etc etc 

end 

回答

0

您可以在after_validation回撥中檢查error[:profile_id].present?。 如果涉及到profile_id中存在錯誤 - 再刪除重複和save

你應該小心,如果您有關於profile_id其他驗證併爲您在這種情況下,具體的錯誤消息的存在。