Posted over 11 years ago. Visible to the public. Linked content.

Manipulate an array attribute using multiple check boxes

E.g. when you're using a tagging Archive gem, you have seen virtual attributes that get and set a string array:

post = Post.last puts post.tag_list # ['foo', 'bar', 'baz'] post.tag_list = ['bam'] puts post.tag_list # ['bam']

If you would like to create a form displaying one check box per tag, you can do this:

- form_for @post do |form| = form.check_box :tag_list, { :multiple => true }, 'foo', nil = form.check_box :tag_list, { :multiple => true }, 'bar', nil = form.check_box :tag_list, { :multiple => true }, 'bam', nil = form.check_box :tag_list, { :multiple => true }, 'baz', nil

For a post with the tags "foo" and "bar", this will render the form like this:

[x] foo [x] bar [ ] baz [ ] bam

The check_box helper will check whether the given value is included in the tag_list array. It also survives form round trips as expected when validation errors occur.

If the form above is submitted, it will send the following params:

{ :post => { :tag_list => ['foo', 'bar', '', '', ''] } }

Note how one empty string is sent for every check box. This is a feature which allows you to uncheck all checkboxes. Your tagging gem will usually filter those out automatically.

(Discovered by snatchev Archive on APIdock Archive )

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Henning Koch
Last edit:
over 11 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more