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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With