views:

16

answers:

2

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
A: 

it's because by default tags is an Array in MongoMapper like you define it. So you can try tags.empty? instead of tags.nil?

In last case tags becomes nil because you try get first element of tags, but there are no one inside. Just nil. You tags becomes nil.

shingara
Thanks! This wasn't my main problem though. I updated the question to be more clear.Also, by the time preen_tags is called, according to the debugger, tags is indeed nil.
Dex
A: 

Looks like converting the String to an Array inside the controller before passing it to the Model has solved things.

Dex