动态选择框 - 根据之前的选择填充可用选项 - Rails& AJAX

时间:2016-06-26 08:37:32

标签: ruby-on-rails ajax ruby-on-rails-4

动态选择框 - 根据之前的选择填充可用选项 - Rails& AJAX

我一直在尝试在我的个人资料表单上创建一个动态选择框,根据学生选择的大学,表单自动提供适当的评分等级以选择作为子选择框。然而,辅助选择框(评级)永远不会填充......唉

谁能看到我在这里失踪的东西?

路线

resources :student_profiles do
    get 'update_ranks', as: 'update_ranks'
  end

模型

rating.rb
    class Rating < ActiveRecord::Base
    belongs_to :university_name
    end

university_name.rb
    class UniversityName < ActiveRecord::Base
    has_many :ratings
    end

控制器

class StudentProfilesController < ApplicationController

before_action :require_user
respond_to :html, :json
def edit
@universitynames = UniversityName.all
        @ratings = Rating.all
       @studentprofile = StudentProfile.find(current_user.student_profile.id)
  end

  def update_ranks
    @ratings = Rating.where("university_name_id = ?", params[:university_name_id])
    respond_to do |format|
      format.js
  end 
End

编辑 - 视图

<%= s.select :universityname, options_for_select(@universitynames.collect { |country|
    [country.name.titleize, country.id] }, 1), {}, { id: 'universitynames_select' } %>

                            <%= s.select :initialgpa, options_for_select(@ratings.collect { |rating|
    [rating.name.titleize, rating.id] }, 0), {}, { id: 'ratings_select' } %>

studentprofile.js.coffee(javascripts / updateranks.js.coffee)

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

updateranks.js.coffee(student_profiles / updateranks.js.coffee)

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

_rating.html.erb - partial(Ratings / _rating.html.erb)

<option value="<%= rating.id %>"><%= rating.name.titleize %></option>

我觉得这与我的路线有关,但我真的没有AJAX或JS的经历...

0 个答案:

没有答案