Rails3 Cocoon Validate Nested Field Count

僤鯓⒐⒋嵵緔 提交于 2019-12-11 08:20:29

问题


I'm having issues validating with cocoon and the number of fields a model is allowed. Using cocoon, rails3, I have a nested form whereby my locations have many links.

I need to restrict the number of links each location has to 5.

In my location.rb model, I have this:

 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

   ...

Adding up to 5 links, all works fine.

If I add 6 links and save, I get an error. Also good.

The problem is when I try and remove the links - it would seem the link is only removed after the save (I think). If I therefore remove all fields, I still get an error.

Any suggestions? Is there another way to validate?


回答1:


Hm. You can try something like this

 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


来源:https://stackoverflow.com/questions/10080488/rails3-cocoon-validate-nested-field-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!