如何在保存模型之前使用act-as-taggable-on格式化标签?
我在我的ruby on rails项目中使用以下gem:
gem 'acts-as-taggable-on', '~> 2.3.1'
我已将兴趣标签添加到我的用户模型中。
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
假设最后一个用户已经拥有兴趣标签:篮球,高尔夫,足球 如果我改变了像
这样的兴趣u = User.last
u.interest_list = "cats, dogs, rabbits"
u.save
然后u.interest_list将是[“猫”,“狗”,“兔子”]
但是,u.interests仍然是一系列与篮球,高尔夫,足球相关的标签对象
如何在保存标签之前确保标签已格式化?
答案 0 :(得分:1)
由于某些原因,您的before_save
回调需要在模型中acts_as_taggable_on
之前,正如Dave在此指出:https://github.com/mbleigh/acts-as-taggable-on/issues/147
我确认这适用于rails(3.2)和act-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