There are tons of code snippets online for dealing with checkboxes in Rails with a SQL-type database, but during my frantic search the other day I couldn’t find much on displaying the elements of an array field in Mongo. This snippet uses gem Rails Bootstrap Forms (gem ‘bootstrap_form’). Thanks to my heroic team lead Colin at Code for DC and this Stack Overflow post http://stackoverflow.com/questions/21568957/using-checkboxes-to-submit-values-to-an-array for helping me to work out a solution.

Model

class Ice_Cream
  include Mongoid::Document
  field :size, type: String
  field :flavors, type: Array
end

Controller

class Ice_CreamsController < ApplicationController

  def create
    #standard create action
  end

  def ice_cream_params
    params.require(:ice_cream).permit(:size, :flavors => [])
  end
end

View using Bootstrap

<p style="font-weight:bold">Flavors</p> 
<%= f.form_group :flavors do %>
  <%= f.check_box :flavors, { label: 'chocolate', name: 'ice_cream[flavors][]', 
                  checked: ice_cream.flavors.include?('chocolate'), namespace: 'chocolate' }, 'chocolate', '' %>
  <%= f.check_box :flavors, { label: 'vanilla', name: 'ice_cream[flavors][]', 
                  checked: ice_cream.flavors.include?('vanilla'), namespace: 'vanilla' }, 'vanilla', '' %>
  <%= f.check_box :flavors, { label: 'strawberry', name: 'ice_cream[flavors][]', 
                  checked: ice_cream.flavors.include?('strawberry'), namespace: 'strawberry' }, 'strawberry', '' %>
  <%= f.check_box :flavors, { label: 'toffee', name: 'ice_cream[flavors][]', 
                  checked: ice_cream.flavors.include?('toffee'), namespace: 'toffee' }, 'toffee', '' %>
  <%= f.check_box :flavors, { label: 'rocky_road', name: 'ice_cream[flavors][]', 
                  checked: ice_cream.flavors.include?('rocky_road'), namespace: 'rocky_road' }, 'rocky_road', '' %>      
<% end %>    

The namespace is used to keep all the checkboxes from having the same id. Another but sprawling alternative is to use the Rails helpers check_box_tag and label_tag:


<div>
  <%= check_box_tag('ice_cream[flavors][]', 'rocky_road', 
    @ice_cream.flavors.include?('rocky_road')) %>
  <%= label_tag('rocky_road') %>
</div>  

I’m still very new to the ways of Mongo but it was interesting working with the array type field.

Tags:

In categories: databases, Rails

COMMENTS

LEAVE A REPLY

Only the name field is required. Your email will not be published.