Search code examples
ruby-on-railscheckboxformtastic

Formtastic pre-check few checkboxes


I'm trying to manually tell formtastic to check a few checkboxes. @some_array currently has an element called checked which exists for each member.

= f.input :cboxes, label: "CBoxes", as: :check_boxes, 
    collection: @some_array.map { |a| [a[:name], a[:id]] }

I've tried to set the input_html to { checked: 'checked' } (How to pre-check checkboxes in formtastic) but this checks all checkboxes, not just the select few that I want.

The contents of @some_array are coming via an API, and I can't change the database structure (Ruby on Rails + Formtastic: Not checking checkboxes for multiple checked answers)

Suggestions?


Solution

  • If you are editing an ActiveModel, you don't need to "manually select checkboxes".

    Let's consider a simple example with a single User model which has fields username and roles. Roles field is a string column, which Rails serializes as an Array. It might also be has_many relation to other ActiveModel, but we assume it's an Array for simplicity.

    User is defined in user.rb:

    class User < ActiveRecord::Base
      serialize :roles, Array
    end
    

    Now you can "assign manually" desired roles to User in your controller:

    @user = User.new(username: 'dimakura', roles: ['admin', 'editor'])
    

    and define form in your view:

    <%= semantic_form_for @user do |f| %>
      <%= f.input :username %>
      <%= f.input :roles, as: :check_boxes, collection: ['owner', 'admin', 'editor', 'viewer'] %>
    <% end %>
    

    In given example only "admin" and "editor" roles will be pre-selected in form. The "owner" and "viewer" role won't be selected.

    Update Official documentation states:

    Formtastic, much like Rails, is very ActiveRecord-centric.

    But actually it's not a big challenge to create ActiveRecord-compatible model yourself. An example of doing this can be found in this blog post.