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整理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值