簡體   English   中英

一個輸入依賴於 activeadmin 表單中的其他輸入字段

[英]One input dependent on other input field in activeadmin form

假設我有一個 model:

class User
 has_many :books
end

class Book
 belongs_to :user
end

現在在活動管理員中,我想當我 select 任何用戶時。 該表單將僅顯示該用戶創建的書籍。

forms do |f|
 f.inputs do
  f.input :user, as: :select, collection: User.all
  f.input :books, as: :select,  collection: Book.all
 end
 f.actions
end      

替換Book.all的查詢是什么?

這項工作對我來說取決於 Rails 6.0.4 上的依賴“選擇”

楷模

class Organization < ApplicationRecord 
 belongs_to :sector
 belongs_to :sub_sectors
end

class Sector < ApplicationRecord 
 has_many :sub_sectors
end

class SubSector < ApplicationRecord 
 belongs_to :sector
end

活動管理表格

ActiveAdmin.register Organization do
  form do |f|
    f.inputs "Details" do
        f.input :sector, as: :select, collection: Sector.all
        f.input :sub_sector_id, as: :select, collection: ([]) # The input is initialized without values
    end
    f.actions
  end
end

您必須執行以下操作:

  1. 創建一個返回子扇區的 controller。

     class SubSectorsController < ApplicationController def sub_sectors_filter if params[:sector_id] sector = Sector.find(params[:sector_id]) @sub_sectors = sector.sub_sectors else @sub_sectors = [] end render:json => @sub_sectors.collect {|sub_sector| {:id => sub_sector.id, :name => sub_sector.name} } end end
  2. routes.rb文件中添加路由。

     get 'sub_sectors_filter/' => 'sub_sectors#sub_sectors_filter'
  3. Inspect with your web browser console your selects, and use a CSS selector to create a jQuery object for the sector select, something like:

     $('#organization_sector_id')
  4. 在文件/app/assets/javascripts/active_admin.js中添加這段代碼,該文件負責調用生成的 controller,並添加它返回的選項。

     //= require active_admin/base $(function () { $('#organization_sector_id').on('change', function () { $('#organization_sub_sector_id option').remove(); // Remove all <option> child tags. $.getJSON(`/sub_sectors_filter`, {sector_id: $(this).val()}, function(result){ // Documentation on getJSON: http://api.jquery.com/jQuery.getJSON/ $.each(result, function (i, item) { // Iterates through a collection $('#organization_sub_sector_id').append($('<option>', { // Append an object to the inside of the select box value: item.id, text: item.name })); }); }); }) })

參考:

在我的依賴 select 在 Active Admin 下拉菜單中找不到錯誤(Rails 3.2,Active Admin 1.0)

使用帶有 Json 數據的 Javascript/Jquery 填充 Select 框選項

正如Sampat在評論中提到的,您可以使用 ActiveAdmin 嵌套選擇插件

安裝activeadmin_addons gem 后,您可以使用:

  forms do |f|
    f.inputs do
      f.input :user_id, as: :nested_select,
                        level_1: { attribute: :user_id, collection: User.all },
                        level_2: { attribute: :book_id, collection: Book.all }
    end
    f.actions
  end


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM