2

这似乎是一个非常受欢迎的问题,尽管我还没有找到适合我的教程或线程。我在表单中有两个下拉菜单,团队类型和用户角色,其中用户角色取决于团队类型。团队类型的选项作为数组存储在模型中,因为只有 5 个选项(艺术家、场地、发起人、独立、其他)。我想做的是从模型中获取用户角色的选择,并根据团队类型选择正确的数组。这可能吗,还是我需要为每个团队类型创建模型并将 ID 传递给连接表以选择正确的用户角色?谢谢你。

模型

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>
4

1 回答 1

1

我认为你应该通过添加 javascriptonChange函数来完成 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

希望这会有所帮助。

于 2016-07-19T19:07:33.237 回答