Skip to main content

Display collection_check_box for Has_and_belongs_to_many association

Rails • Asked by Lee Terng Gio

Hi, I want to display a list of check boxes, below is my code,

<%= f.collection_check_boxes :job_ids, @current_user.jobs.all, :id, :job_name  do |b| %>    
        <div class="collection-check-box">
          <%= b.check_box %>
          <%= b.label %>
        </div>
<% end %>

It works well which display a list of Job_name which can be selected by the user. However, I want to display more information about the job, not just the job_name only, but also the job_type as well. How would I achieve that? I want it to be display in the check_box like this -> System Engineer, Full Time


Hi Lee,

Check out: https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

In the first example, you'll see they made a function to return whatever they'd like to display:

  def name_with_initial
    "#{ first_name.first }. #{ last_name }"
  end

So in your case, you could do something like:

  def name_with_type
    "#{ job_name } - #{ job_type }"
  end

Then update your view like so:

  <%= f.collection_check_boxes :job_ids, @current_user.jobs.all, :id, :name_with_type  do |b| %>    
    <div class="collection-check-box">
      <%= b.check_box %>
      <%= b.label %>
    </div>
  <% end %>

I haven't tested this, so you may have to play with it some.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.