Thursday, January 19, 2012

mongoid array field and rails form

by Sandip Ransing 0 comments

mongoid document supports array as field. array field in mongoid document is a ruby array but its quite complex to manage array field in rails forms.
After lot of google and reading comments from stack-overflow at last i felt helpless. Finally after doing research on rails form helper object(form_for, fields_for) am pleased to get it working as expected :)
In below example, product can have multiple categories
class Product CATEGORIES = %w(Apparel Media Software Sports Agri Education) include Mongoid::Document field :name, :type => String field :categories, :type => Array end Here is form code
= form_for(@product) do |f| = f.text_field :name - Product::CATEGORIES.each do |category| = f.check_box :categories, :name => "product[categories][]", category
Here is products controller code
class ProductsController < ApplicationController before_filter :load_product, :only => [:new, :create] [...] # We don't need new action to be defined def create @product.attributes = params[:product] # Here we need to reject blank categories @product.categories.reject!(&:blank?) if @product.save flash[:notice] = I18n.t('product.create.success') redirect_to(:action => :index) else render :action => :new end end [...] private def load_product @product = Product.new end end

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter