Rails_Admin related dropdowns

1.5k views Asked by At

Is there a way to filter a dropdown list based on another dropdown's value ?
For example, if we have: Class and Student Models where Student have class_id; is there a way to filter the Students shown in the dropdown based on the selected Class ?

EDIT

Apparently, rails_admin gem has an association relationship which I was looking for; but it doesn't work perfectly.

3

There are 3 answers

0
Roc Khalil On BEST ANSWER

This is the related link: https://github.com/sferik/rails_admin/wiki/Associations-scoping which edited the origin question

3
Shannon On

If you can use Javascript, this Railscast will help you:

In this instance, your dropdowns may look like this:

<%= f.collection_select :class_id, Class.all, :id, :name, {:prompt => "Select a Class"}, {:id => "class"} %>

<%= f.collection_select :student_id, Student.all, :id, :name, {:prompt => "Select a Student"}, {:id => "student"} %>

And you would use Javascript to change the options in the Student dropdown. You can get the value of the class using:

class_id = $("#class").find(":selected").text()
5
wjordan On

Given two <select> elements "Class" and "Student", with the Student list containing data-class_id attributes referencing values from the Class list (see snippet below), you can filter the "Student" dropdown based on the "Class" dropdown's value using the following vanilla-JavaScript code:

var firstSelectId = "Class";
var secondSelectId = "Student";
var data_attr = "class_id";
this.addEventListener("DOMContentLoaded", function(event) {
  var firstSelect = document.getElementById(firstSelectId);
  var secondSelect = document.getElementById(secondSelectId);
  firstSelect.addEventListener("change", function(event) {
    var value = event.target.value;
    Array.prototype.forEach.call(secondSelect.options, function(item) {
      item.style.display = (item.dataset[data_attr] === value) ? 'inline' : 'none';
    });
    var selected = secondSelect.selectedOptions[0];
    if (selected && selected.dataset[data_attr] !== event.target.value) {
      secondSelect.selectedIndex = -1;
    }
  });
  firstSelect.dispatchEvent(new Event('change'));
});
<form id="myform">
  Select a class and student:
  <select id="Class">
    <option value="1">Class1</option>
    <option value="2">Class2</option>
    <option value="3">Class3</option>
  </select>
  <select id="Student">
    <option value="StudentA" data-class_id="1">A</option>
    <option value="StudentB" data-class_id="2">B</option>
    <option value="StudentC" data-class_id="3">C</option>
    <option value="StudentD" data-class_id="2">D</option>
    <option value="StudentE" data-class_id="1">E</option>
    <option value="StudentF" data-class_id="1">F</option>
  </select>
</form>