Rails 3.1 - Active_admin and checkboxes

This question is really two questions.

  • Select all buttons - Active_admin uses formtastic to render forms, so I'm going to ask in the context of formtastic. How to create a button that will select all the checkboxes on the page? I could do this using JavaScript, but I'm not sure how to do this in formtastic.
  • Set the collection based on the selection value . I have a drop-down menu that allows people to select "Courses" from the list. Students are enrolled in the courses, so I want to be able to display a list of flags of students enrolled in the course. That is: the list of students will change if the user chooses a different course.

    course.rb

    has_and_belongs_to_many: students

    student.rb

    has_and_belongs_to_many: courses

+4
source share
2 answers

Formtastic doesn’t have a simple solution for the “select all” checkbox, if you use JQUERY you can do it

In your student.rb model add

 attr_accessor :select_all_courses f.inputs "Courses" do f.input :select_all_courses, :as => :boolean, :label => 'SELECT ALL', :input_html => {:onclick => "jQuery.each( $('.student_courses_checkboxes'), function() { this.checked = $('.all_selector')[0].checked });", :class => "all_selector"} f.input :courses, :as => :check_boxes, :collection => @courses, :input_html => {:class => 'student_courses_checkboxes'} end 

The best you can do in active admin with formtastic:

In the form of a course

 f.input :students, :as => :check_boxes, :collection => @students 
+10
source

Since I need to automatically add the Select All / Select No buttons for the WHOLE group, I add a bit of javascript to active_admin.js (renamed from active_admin.js.coffee since it does not use CoffeeScript).

 //= require active_admin/base $( document ).ready(function() { var $select_btns = $('<li class="choice"><div class="select-btn-container"><button class="select_all">Select all</button><button class="select_none">Deselect all</button></div></li>'); $('.inputs .check_boxes').each(function (i, el) { $(el).find('.choices-group').prepend($select_btns.clone()); }); $('.inputs') .on('click', '.select_all', function () { var $check_boxes = $(this).parents('.choices-group').find('input'); $check_boxes.each(function () { this.checked = true; }); return false; }) .on('click', '.select_none', function () { var $check_boxes = $(this).parents('.choices-group').find('input'); $check_boxes.each(function () { this.checked = false; }); return false; }); }); 

Working with ActiveAdmin 1.0.0 on Rails 4.0.4. Hope this helps.

0
source

All Articles