Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I group checkboxes by parent with Active Admin (formatastic)

This is the category model. A category can belong to another category.

class Category < ActiveRecord::Base
  attr_accessible :title, :parent_id

  has_and_belongs_to_many :products, :join_table => :products_categories

  belongs_to :parent, :foreign_key => "parent_id", :class_name => "Category"
  has_many :categories, :foreign_key => "parent_id", :class_name => "Category"
end

This is the product model:

class Product < ActiveRecord::Base
  attr_accessible :comment, location_id, :category_ids
  has_and_belongs_to_many :categories, :join_table => :products_categories
  belongs_to :location
end

In the Active Admin form for a product I want to hierarchically order the checkboxes based on their parent_id e.g.

  • Category 1 [ ]
    • Category 2 [ ]
    • Category 3 [ ]
  • Category 6 [ ]
    • Category 4 [ ]
  • Category 5 [ ]
  • Category 7 [ ]

Below is as far as I've got with the form:

ActiveAdmin.register Product do
    form do |f|
      f.inputs "Product" do
      f.input :comment
      f.input :categories, :as => :check_boxes
      f.input :location
    end
    f.buttons
  end
end

Currently the form pulls in the checkboxes and saves the data correctly but I'm not sure where to begin with grouping them. I looked through the documentation but couldn't see anything obvious.

like image 650
benjamunky Avatar asked Oct 19 '12 09:10

benjamunky


1 Answers

This may beaddressed in part by user Hopstream's ActiveAdmin -- How to display category taxonomy? (in tree type hierarchy) question. It is different enough because of Formtastic to present some interesting challenges, however, namely that formtastic straight up can't do this "out of the box" at all.

It is possible, however to extend and override Formtastic's Formtastic::Inputs::CheckBoxesInput class in order to add the ability to noodle through the nesting logic. Fortunately, this problem has also already happened for someone else.

Github user michelson's Formtastic check boxes with awesome_nested_set gist will provide you with a class you can add to your rails app, placing the acts_as_nested_set line in your Product model and the f.input line necessary for the Formtastic f.inputs "Product" block within your ActiveAdmin.register block, which should actually work unmodified from the structure of your models as:

f.input :categories, :as=>:check_boxes, :collection=>Category.where(["parent_id is NULL"]) , :nested_set=>true

like image 176
jimcavoli Avatar answered Nov 12 '22 19:11

jimcavoli