在保存用户模型之前,如何使用acts-as-taggable-on gem格式化标签?

时间:2013-02-26 01:56:22

标签: ruby-on-rails-3 acts-as-taggable-on before-save

如何在保存模型之前使用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仍然是一系列与篮球,高尔夫,足球相关的标签对象

如何在保存标签之前确保标签已格式化?

1 个答案:

答案 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