Ask A Question

Notifications

You’re not receiving notifications from this thread.

Display collection_check_box for Has_and_belongs_to_many association

Lee Terng Gio asked in Rails

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

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,376+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.