1

I have created model, controller and view with rails scaffold generator:

rails g scaffold Todo description:string tags:array

So I have the model:

class Todo
  include Mongoid::Document
  field :description, :type => String
  field :tags, :type => Array
end

And controller:

def create
    @todo = Todo.new(params[:todo])
    @todo.save

But this case (auto-generated code) I get error that tells me something like:

tags field must be array datatype, but you're trying to use string

So I have fixed the controller:

def create
    #@todo = Todo.new(params[:todo])

    @tmp = params[:todo]
    @tmp["tags"] = @tmp["tags"].split(',')
    @todo = Todo.new(@tmp)

And I'm just wondering if there is any better way to fix my error?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
ceth
  • 44,198
  • 62
  • 180
  • 289

1 Answers1

2

Depends on how your view is structured. From what I see, there must be a single text input or something, into which you input tags, separated by comma. No wonder it comes as a string! In this case your workaround is correct. I would add stripping of leading and trailing whitespace, though.

@tmp["tags"] = @tmp["tags"].split(',').map(&:strip)

To get a real array in params your HTML must look like this:

<input type='text' name='tags[]' />
<input type='text' name='tags[]' />
<input type='text' name='tags[]' />

Where each of these inputs holds a single tag.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 1
    Is it possible to setup rails so scaffold generator will generate the set of input tags (as in your example) ? – ceth Mar 22 '12 at 11:46