I have a MongoMapper model and am trying to convert a comma-delimited string into an Array to be stored.
The main problem is that a string such as tags = "first,second,third"
is not getting converted to an array in the database like ["first","second","third"]
. Instead it is going in as ["first,second,third"]
.
There are some other strange things going on as well:
1) In preen_tags I have to include the unless tags.nil? after every line
2) in preen_tags, using the debugger tags
returns nil
Here is my model
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