Rails 4 Dynamic Collection_Select

时间:2016-07-19 14:48:00

标签: jquery ajax ruby-on-rails-4 collection-select

这似乎是一个非常受欢迎的问题,尽管我还没有找到适合我的教程或主题。我有一个表单中的两个下拉菜单,团队类型和用户角色,其中用户角色取决于团队类型。 Team Type的选项作为数组存储在模型中,因为只有5个选项(Artist,Venue,Promoter,Independent,Other)。我想做的是从模型中获取用户角色的选择,并根据团队类型选择正确的数组。这是可能的,还是我需要为每个团队类型创建模型并将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>

1 个答案:

答案 0 :(得分:1)

我认为你应该通过添加javascript ref.orderByChild("awardedBid").endAt(null) 函数来执行ajax请求。还添加一个新方法来处理这个ajax请求

<强>表格

onChange

Javascript文件

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

<强>控制器

我为waiting_lists控制器添加了路由

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

希望这有用。