动态选择与祖先宝石并选择

时间:2012-11-06 04:19:34

标签: ruby-on-rails activeadmin jquery-chosen ancestry

我正在寻找使用选择和祖先宝石的动态选择,我希望之前有人这样做。

我有大约2000个(类别,子类别和关键字)都在STI中并且具有树结构。在我的表单中,我使用三个选择输入类别|子类别|关键字,但我得到了很大的子类别列表,甚至更大的关键字列表。我想隐藏所有子类别,这些子类别不是预选类别的子类;与关键字相同。

希望这是有道理的,我想做的。我非常感谢任何想法。

到目前为止,我所拥有的所有代码都运行良好。

class Company < ActiveRecord::Base
has_and_belongs_to_many :categories, :join_table => "companies_categories"
has_and_belongs_to_many :subcategories, :join_table => "companies_subcategories"
has_and_belongs_to_many :keywords, :join_table => "companies_keywords"
end

class Category < ActiveRecord::Base
has_ancestry  :cache_depth => true, :depth_cache_column => :ancestry_depth

has_many :subcategories, :class_name => "Category", :foreign_key => :subcategory_id
has_many :keywords, :class_name => "Category", :foreign_key => :keyword_id

belongs_to :category

has_and_belongs_to_many :companies, :join_table => "companies_categories"
has_and_belongs_to_many :companies, :join_table => "companies_subcategories", :association_foreign_key => "subcategory_id"
has_and_belongs_to_many :companies, :join_table => "companies_keywords", :association_foreign_key => "keyword_id"

end  

这是javascript

jQuery(function($){
$(".chosen-input").chosen();
$(".schosen-input").chosen();
$(".kchosen-input").chosen();
});    

这是我的表格

form :html => { :enctype => "multipart/form-data" }  do |f|
f.inputs "New Company" do
  f.input :name,  :required => true
end

f.inputs "Categories" do

  f.input :categories,
          :input_html => { :class => "chosen-input", :multiple => true, :style => "width: 700px;"},
          :collection => Category.where(:ancestry_depth => '2')


  f.input :subcategories,
          :input_html => { :class => "schosen-input", :multiple => true, :style => "width: 700px;"},
          :collection => Category.where(:ancestry_depth => '3')


  f.input :keywords,
          :input_html => { :class => "schosen-input", :multiple => true, :style => "width: 700px;"},
          :collection => Category.where(:ancestry_depth => [4, 5, 6])

end

1 个答案:

答案 0 :(得分:1)

我使用select2,但我认为选择也是可能的。所以,你必须使用ajax请求。 在服务器端定义一个动作,获取一个类别ID(所选类别的id),并返回所选类别id的子类别的集合(以json格式)。然后在客户端(使用jquery或javasciprt),您必须使用json对象填充选择输入。

您可以使用的JQuery事件:http://api.jquery.com/change/

填充选择输入:jQuery-- Populate select from json

在ActiveAdmin中,您必须根据DOM确定选择输入。