Handle MongoDB arrays in Rails Forms
An example post:
{
title: 'Editing MongoDB Arrays in Rails'
tags: ['ruby', 'rails', 'mongodb']
}
Create a model with two new methods like this:
class Post
include Mongoid::Document
field :title, type: String
field :tags, type: Array, default: []
def tags_list=(arg)
self.tags = arg.split(',').map { |v| v.strip }
end
def tags_list
self.tags.join(', ')
end
end
The in your view form, use the following instead of the tags field
<%= f.text_field :tags_list %>
Any comma seperated values in the field, will be saved as individual items in an array.
Example:
post = Post.new
post.tags_list = 'tag1, tag2, tag3'
=> "tag1, tag2, tag3"
post.tags
=> ["Tag1", "Tag2", "Tag3"]
Originally blogged at (http://blog.codiez.co.za/2013/07/editing-mongodb-arrays-in-rails/)
Written by Ismail Dhorat
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#