Rails 4 个动态 Collection_Select

Rails 4 Dynamic Collection_Select

这似乎是一个非常受欢迎的问题,尽管我还没有找到适合我的教程或话题。我在表单中有两个下拉菜单,团队类型和用户角色,其中用户角色取决于团队类型。 Team Type 的选项作为数组存储在模型中,因为只有 5 个选择(Artist、Venue、Promoter、Independent、Other)。我想做的是也从模型中获取用户角色的 selections,根据团队类型使用适当的数组 selected。这是可能的,还是我需要为每个团队类型创建模型并将 ID 传递给 table 到 select 正确的用户角色?谢谢。

型号

class WaitingList < ActiveRecord::Base
  COMPANIES = ['—Select—', 'Artist Team', 'Venue Team', 'Promoter', 'Independent', 'Other']
  ARTIST_TEAM = ['-Select-', 'Artist', 'Manager', 'Tour Manager', 'Production Manager', 'Agent', 'Other']
  VENUE_TEAM = ['-Select-', 'Artist Liason', 'Stage Manager', 'Production Manager', 'Owner', 'Other']
  PROMOTER = ['-Select', 'Talent Buyer', 'Other']
  INDEPENDENT = ['-Select', 'Agent', 'Photo/Video', 'Tour Manager', 'Manager', 'Other']
end 

表格

<div class="form--col">
  <label>Team Type</label>
    <div class="dropdown-wrapper">
      <%= f.collection_select :company_type, WaitingList::COMPANIES, :to_s, :to_s, {:include_blank => false}, {:class => "form--dropdown -team_type"} %>
    </div>
</div>

<div class="form--col -inactive">
  <label>Main Role</label>
    <div class="dropdown-wrapper">
      <%= f.collection_select :user_type, WaitingList::USERS, :to_s, :to_s, {:include_blank => false}, {:class => "form--dropdown", :disabled => "disabled"} %>
    </div>
</div>

我认为你应该通过添加 javascript onChange 函数来完成 ajax 请求。同时添加一个新方法来处理这个 ajax 请求

表格

<div class="form--col">
  <label>Team Type</label>
  <div class="dropdown-wrapper">
    <%= f.collection_select :company_type, WaitingList::COMPANIES, :to_s, :to_s, {include_blank: false}, {onchange: "getRoles();", class: "form--dropdown -team_type"} %>
  </div>
</div>

<div class="form--col -inactive">
  <label>Main Role</label>
  <div class="dropdown-wrapper">
    <%= f.collection_select :user_type, {}, {prompt: 'Main Role'} {:class => "form--dropdown", :disabled => "disabled"} %>
  </div>
</div>

Javascript 文件

function getRoles() {
  var currentRole = $('#company_type :selected').val(); 
  $.ajax({
     url: '/waiting_lists/'+ currentRole +'/get_role',
     dataType: "json",
     success: function(data) {
       $('#user_type').html('');
       for (i in roles) {
         if (roles[i] != undefined) {
           $('#user_type').append("<option value=\""+roles[i]+"\">"+roles[i]+"</option>");
         }  
       }
     } 
  });      
}

控制器

我为 waiting_lists 控制器添加了一条路线

  def get_role()
    if params[:role]
      case params[:role]
      when 'Artist Team'  
        roles = WaitingList::ARTIST_TEAM
      when 'Venue Team'
        roles = WaitingList::VENUE_TEAM
      when 'Promoter'
        roles = WaitingList::PROMOTER
      when 'Independent'
        roles = WaitingList::INDEPENDENT
      when 'Others'
        roles = []
      end      
      render json: {roles: roles}
    end 
  end

路线

为 waiting_lists 控制器

添加了路由
resources(:waiting_lists) do
  collection do
    get(':role/get_role', action: :get_role)
  end
end

希望这对您有所帮助。