我有一个 MongoMapper 模型,正在尝试将逗号分隔的字符串转换为要存储的数组。
主要问题是字符串如tags = "first,second,third"
没有被转换为数据库中的数组,如["first","second","third"]
. 相反,它以["first,second,third"]
.
还有一些其他奇怪的事情发生了: 1)在 preen_tags 我必须包括除非 tags.nil?在 preen_tags 中的每一行 2) 之后,使用调试器tags
返回 nil
这是我的模型
class Template
include MongoMapper::Document
validate :validate_tags
after_validation :preen_tags
key :template_id, ObjectId
key :title, String
key :description, String
key :tags, Array
timestamps!
def validate_tags
errors.add_to_base "You Must Enter At Least 1 Tag." if tags.blank?
end
def preen_tags
#return if tags.nil? #why doesn't this work??
#only alphanumeric chars allowed, except hyphens and commas
tags = tags[0] if tags.is_a?(Array)
tags = tags.gsub(/[^0-9a-z\-\,]/i, '') unless tags.nil?
#convert spaces to hyphens
tags = tags.gsub(/\s/, '-') unless tags.nil?
tags = tags.split(",") unless tags.nil?
end
end