2012-04-09 93 views
1

我遇到問題驗證與繭和模型允許的字段數。使用cocoon,rails3,我有一個嵌套表單,我的位置有很多鏈接。Rails3繭驗證嵌套字段計數

我需要限制每個位置都有鏈接的數量爲5

在我location.rb模型中,我有這樣的:

class Location < ActiveRecord::Base 

    has_many :links 
    accepts_nested_attributes_for :links, :reject_if => lambda { |a| a[:link_name].blank? }, :allow_destroy => true 
    validate :check_link_count 

    ... 

    def check_link_count 
     if self.links.count > 5 
     self.errors.add :base, "No more than 5 links allowed." 
     end 
    end 

    ... 

添加最多5個環節,一切工作正常。

如果我添加6個鏈接並保存,則會出現錯誤。也不錯。

問題是,當我嘗試並刪除鏈接 - 它似乎鏈接只保存(我認爲)後刪除。如果我因此刪除所有字段,我仍然收到錯誤。

有什麼建議嗎?有另一種驗證方法嗎?

回答

3

嗯。你可以嘗試這樣的事情

def check_link_count 
    if self.links.reject(&:marked_for_destruction?).count > 5 
     self.errors.add :base, "No more than 5 links allowed." 
    end 
end 
+0

太棒了,那很容易。將不得不閱讀marked_for_destruction S. – simonmorley 2012-04-09 22:30:31