Search code examples
ruby-on-railsvalidationacts-as-taggable-on

validate acts as taggable on


I am using acts-as-taggable-on to add tagging. I have this in my model:

acts_as_taggable 
validates_inclusion_of :tag_list, in: %w( bug feature )

However, in rails console if I try:

i = Issue.find(1)
i.tag_list = "bug"
i.save

validation fails and issue tag_list is not saved. If i remove validation line then of course I am able to add tag_list. I tried to write my custom validation too:

validate :tag_list_inclusion

  def tag_list_inclusion
    tag_list.each do |tag|
      return false unless %w(bug feature).include?(tag)
    end
    return true
  end

My custom validation does work as in it always returns true and always passes validation (even when it shouldn't). only validation which works as it should is:

validates_presence_of :tag_list

Solution

  • I found the answer here: http://guides.rubyonrails.org/active_record_validations.html#custom-methods

    My custom validator was:

      def tag_list_inclusion
        tag_list.each do |tag|
          errors.add(tag,"is not valid") unless %w(bug feature).include?(tag)
        end
      end