带有Rails 4的动态选择框

时间:2016-04-01 23:41:42

标签: javascript jquery ruby-on-rails ajax coffeescript

我尝试制作动态选择框(一个框在另一个框中选择信息),但有一些麻烦。

的routes.rb

get "students/new/update_tutors" => 'students#update_tutors', as: 'update_tutors'  

students_controller.rb

def update_tutors
    admin = Administrators.find(params[:administrator_id])
    #@tutors = admin.tutors.map{|t| [t.info.name, t.id]}
    debugger
    @tutors = Tutor.where(administrator_id: params[:administrator_id])
    respond_to do |format|
       format.js
    end
end
def new
    @user = Student.new
    @is_super_adm = is_super?
    if @is_super_adm
      @tutors = Tutor.all.map { |t| [t.info.name, t.id] }
      @admins = Administrator.where(is_super: false).map { |adm| [adm.info.name, adm.id] }
    else
      @tutors = Tutor.where(administrator_id: session[:type_id]).map { |t| [t.info.name, t.id] }
    end
end

new.html.erb

<%= form_for @user, remote: true do |student_form| %>
<!--....-->
<%= label_tag :administrator_id, "Choose local administrator" %><br/>
<%= select_tag :administrator_id, options_for_select(@admins), {id: 'administrator_selection'}  %><br/>
<!--....-->
<%= student_form.label :tutor_id, "Choose Tutor" %><br/>
<%= student_form.select :tutor_id, options_for_select(@tutors), {} , {id: 'tutor_selection'}%>  

students.coffee

$ ->
  $(document).on 'change', '#administrator_selection', (evt) ->
    $.ajax 'update_tutors',
      type: 'GET'
      dataType: 'script'
      data: {
        administrator_id: $("#administrator_selection option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic country select OK!")

update_tutors.coffee

$("#tutor_selection").empty()
    .append("<%= escape_javascript(render(:partial => @tutors)) %>")

我尝试将alert('msg')插入students.js.coffee,事件有效,所以我确定问题出在$.ajax但这是我第一次使用ajax而且我可以&找不到错误。

更新

我猜问题是在路由中,但我不明白为什么它会调用students/update_tutor来代替students/new/update_tutor
日志
    开始GET&#34; / students / update_tutors?administrator_id = 3&amp; _ = 1459590346845&#34;对于127.0.0.1在2016-04-02 11:47:01 +0200
    由StudentsController处理#show为JS
    参数:{&#34; administrator_id&#34; =&gt;&#34; 3&#34;,&#34; _&#34; =&gt;&#34; 1459590346845&#34;,&#34; id&#34 ; =&GT;&#34; update_tutors&#34;}

固定

我将update_tutors中的$.ajax更改为'new/update_tutors',并将Administrators.find(...)中的update_tutors方法中的错误修正为Administrator.find(...)

0 个答案:

没有答案