开发者

Replace 'collection_select, :multiple => true' with multiple 'check_box' options in Rails

How do you replace a collection_select (with :multiple => true) with a list of check_box options, such that there is a check_box option for each object in the collection?

Is there an elegant way to implement this using form builders (i.e. without using *_tag he开发者_如何学Golpers)? I'd like to lean on ActiveRecord's built in functionality as much as possible...


I don't think there's a built-in "elegant" way to do this.

This railscast should get you going, though:

  • http://railscasts.com/episodes/17-habtm-checkboxes
  • http://asciicasts.com/episodes/17-habtm-checkboxes (text versionn)


You can do it like this (example using HAML).

%fieldset
  Colors I like
  - %w[red blue].each do |color|
    = f.label color 
    = f.check_box :colors_liked, {multiple: true}, color, nil

The nil option at the end prevents Rails from building a hidden checkbox by the same name with a 0 value, which you definitely don't want if you're going for multiple selection.

This produces:

<label for="colors_liked_red">Red</label>
<input id="my_form_colors_liked_red" \
  name="my_form[colors_liked][]" type="checkbox" value="red">

<label for="colors_liked_blue">Blue</label>
<input id="my_form_colors_liked_blue" \
  name="my_form[colors_liked][]" type="checkbox" value="blue">

When the form is submitted, the parameters will contain an array of the values of the checked options.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜