Search code examples
ruby-on-railsformscheckboxsimple-form

Display checkbox from loop elements


I have a form to create a new recipe. Each recipe can have multiple tags. I would like to display all the tags possibility and allow the user to check or uncheck them. I'm able to have a pretty display of the tags but I don't know how to turn them into checkboxes... They have to be saved in the field all_tags as an array.

= simple_form_for @recipe, html: {multipart: true} do |f|
  - if @recipe.errors.any?
    #errors
      %p
        = @recipe.errors.count
        prohibited this recipe from being saved:
      %ul
        - @recipe.errors.full_messages.each do |message|
          %li= message
  .row
    .panel-body
      = f.input :title, input_html: {class: 'form-control'}
      = f.input :description, placeholder: 'Dites nous ce que vous aimez dans cette recette ? où l\'avez-vous découverte ? avec quoi l\'accompagnée vous ? ...', input_html: {class: 'form-control'}
      = f.input :image, input_html: {class: 'form-control'}
      .tag-wrapper
        - @tags.each do |tag|
          %ul
            %li.tag.fa.fa-plus
              = tag.name

Solution

  • Try this out:

    .tag-wrapper
      - @tags.each do |tag|
        = check_box_tag tag.name
    

    EDIT:

    If you need to save them as array try this solution:

    = f.input :all_tags, :as => :check_boxes, :collection => @tags