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?
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.
To get a real array in params your HTML must look like this:
Where each of these inputs holds a single tag.