如何在保存模型之前使用acts-as-taggable-on 格式化标签?
我在我的 ruby on rails 项目中使用以下 gem
gem 'acts-as-taggable-on', '~> 2.3.1'
我已将兴趣标签添加到我的用户模型中。
用户.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
假设最后一个用户已经有兴趣标签:篮球,高尔夫,足球如果我改变兴趣喜欢
u = User.last
u.interest_list = "cats, dogs, rabbits"
u.save
那么 u.interest_list 将是 ["cats", "dogs", "rabbits"]
但是,u.interests 将保留与篮球、高尔夫、足球相关的标签对象数组
如何确保在保存标签之前对标签进行格式化?