Rails3 Cocoon Validate Nested Field Count
-
30-05-2021 - |
Question
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?
Solution
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow