ActiveAdmin扩展:级联选择

ActiveAdmin扩展:级联选择


1、在active_admin.js的同级目录下新建一个common.js文件,
   然后在active_admin.js中加入
     //= require common
   (若新建的文件与active_admin.js不在同级目录下,则require后面的文件路径需相应修改)


2、common.js中相关代码如下:


   此处的article_title为form表单自动生成,格式为“[模型]_[字段]”,根据实际情况作相应修改。

    $(function() {
      $('#article_title').change(function() {
        $.ajax({
          url: '/admin/articles/get_secondary_subject_by_subject',
          type: 'POST',
          data: {
            subject_id: $(this).val()
          },
          dataType:'json',
          headers: {
            'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
          },
          success: function(data) {
            $('#article_content').html("");
            var str = '';
            for (var i = 0; i < data.length; ++i) {
              str += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
            };
            $('#article_content').append(str);
          },
          error: function() {

          }
        });
      });
    });

3、rb文件中相关代码如下:

   collection_action :get_secondary_subject_by_subject, :method => :post do
     @subject_id = params[:subject_id]
     @secondary_subjects = Subject.where("parent_subject_id = ?", @subject_id)
     render :json => @secondary_subjects.to_json(:only => [:id, :name]) and return
   end

   controller do
     def new
       @article = Article.new
       @subjects = Subject.order("id asc").where("parent_subject_id is null")
       @secondary_subjects = Subject.order("id asc").where("parent_subject_id = ?", @subjects.first.id)
     end

     def edit
       @subjects = Subject.order("id asc").where("parent_subject_id is null")
       @secondary_subjects = Subject.order("id asc").where("parent_subject_id = ?", @subjects.first.id)
     end
   end

   f.input :title, :as => :select, :collection => subjects, :include_blank => false
   f.input :content, :as => :select, :collection => secondary_subjects, :include_blank => false


以上内容由Bruce.Xue整理。

猜你喜欢

转载自blog.csdn.net/feng88724/article/details/49181155