简体   繁体   中英

Rails 3.1 - Active_admin and Checkboxes

This question is really two questions.

  1. Select all button - Active_admin uses formtastic to render forms, so I'm going to ask in the context of formtastic. How would I create a button that selects all the checkboxes on the page? I could do it using JavaScript, but I'm unsure of how to do this in formtastic.
  2. Set collection based on select value . I have a drop down menu that let's people choose from a list of "Courses". Students are enrolled in courses, so I want to be able to display a checkbox list of student enrolled on the course. Ie: The list of students will change if the user selects a different course.

    course.rb

    has_and_belongs_to_many :students

    student.rb

    has_and_belongs_to_many :courses

Formtastic does not have an easy solution for a "select all" checkbox, if you are using JQUERY you can do this

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 is:

In your course form

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

Since I need to automatically add Select All/Select None buttons to ALL checkbox group input, I add a bit of javascript to active_admin.js (renamed from active_admin.js.coffee since it don't 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 on ActiveAdmin 1.0.0 on Rails 4.0.4. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM