简体   繁体   中英

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 eg

  • 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.

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

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