I am using acts-as-taggable-on gem and I am trying to make some sort of the validation on number of tags. I followed this tutorial and it works fine: http://railscasts.com/episodes/382-tagging
I have an article which acts as taggable. For now I validate that tags need to be present and number of characters:
class Article < ActiveRecord::Base
acts_as_taggable
validates :tag_list, presence: true, length: { maximum: 100 }
end
This is not really good solution for tags as there are many of them with many different sizes and they are separated by commas. How can I set required minimum and maximum number of tags which need to be connected with article? I would like to set minimum to 3 tags and maximum to 10 tags so length of text is not a good solution.
Thank you for your help :)
This example should point the right direction:
validate :tag_list_validation
def tag_list_validation
errors[:tag_list] << "3 tags minimum" if tag_list.count < 3
errors[:tag_list] << "10 tags maximum" if tag_list.count > 10
self.tag_list.each do |tag|
errors[:tag_list] << "#{tag} must be shorter than 100 characters maximum" if tag.length > 100
end
end
EDIT: Solution to your question:
class Article < ActiveRecord::Base
acts_as_taggable
validate :tag_list_count
def tag_list_count
errors[:tag_list] << "3 tags minimum" if tag_list.count < 3
errors[:tag_list] << "10 tags maximum" if tag_list.count > 10
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With