Skip to content

Checkbox group field

Inza edited this page Sep 20, 2012 · 1 revision

In order to make a checkbox group field you should do the following:

For the purpose of our example we assume that you have two models - a Worker and a Skill, and the worker has_and_belongs_to_many :skills and skill has_and_belongs_to_many :workers. You have create all necessarily migrations and migrated your db.

  • Create your model and setup a has_many & belongs_to association in a classic Rails (or AR/Mongoid) way.
  • Configure your field in the rails_admin.rb initializer file by adding a partial clause to your field:
config.model Worker do
  edit do
    group :default do
      field :skills do
        partial "form_checkboxes_multiselect"
      end
    end
  end
end

The important line there is partial "form_checkboxes_multiselect" which tells to Rails Admin to use our new partial for rendering field skills.

  • Because we have a bi-directional association we could want to have the ability to chose workers even in our skills administration. This could be done be a very similar way by adding the following to the rails_admin.rb initializer file:
config.model Skill do
  edit do
    group :default do
      field :workers do
        partial "form_checkboxes_multiselect"
      end
    end
  end
end
  • Last optional but recommended step is to set inversion information to the configuration. This will be used by Rails Admin to eliminate circular nested forms, etc. This could be done by adding two new lines to the rails_admin.rb initializer file just before our partial clauses:
config.model Worker do
  edit do
    group :default do
      field :skills do
        inverse_of :workers
        partial "form_checkboxes_multiselect"
      end
    end
  end
end

config.model Skill do
  edit do
    group :default do
      field :workers do
        inverse_of :skills
        partial "form_checkboxes_multiselect"
      end
    end
  end
end
  • Now restart your server and try to add, or edit Worker or Skill. And you are done!

Clone this wiki locally