1
votes

How can I format tags using acts-as-taggable-on before saving the model?

I am using the following gem in my ruby on rails project

gem 'acts-as-taggable-on', '~> 2.3.1'

I have added interests tags to my user model.

user.rb

class User < ActiveRecord::Base
  acts_as_ordered_taggable_on :interests
  scope :by_join_date, order("created_at DESC")

  rolify
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :interest_list

  # this does not work
  before_save :clean_my_tags

  # this also does not work
  # before_validation :clean_my_tags

  def clean_my_tags
    if @interest_list
      # it appears that at this point, @interest_list is no longer a string, but an
      # array of strings corresponding to the tags
      @interest_list = @interest_list.map {|x| x.titleize}
    end
  end
end

Suppose that the last user already has the interest tags: basketball, golf, soccer If I change the interests like

u = User.last
u.interest_list = "cats, dogs, rabbits"
u.save

Then u.interest_list will be ["cats", "dogs", "rabbits"]

However, u.interests will remain an array of tag objects associated with basketball, golf, soccer

How can I make sure that the tags are formatted before tags are saved?

1

1 Answers

1
votes

For some reason your before_save callback needs to come before acts_as_taggable_on in your model, as Dave points out here: https://github.com/mbleigh/acts-as-taggable-on/issues/147

I confirmed this works with rails (3.2) and acts-as-taggable-on (2.3.3):

class User < ActiveRecord::Base

  before_save :clean_my_tags

  acts_as_ordered_taggable_on :interests

  def clean_my_tags
    if interest_list
      interest_list = interest_list.map {|x| x.titleize}
    end
  end
end