使用f.select选择课程并自动输入字段count_stud值

时间:2014-04-29 15:22:27

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

有一种形式可以选择年份和课程。另一个字段不可见(它应该改变学生的数量,这对应于所选择的课程)。使用f.select选择一个课程,并自动输入字段count_stud值,该值等于该课程的学生人数。这该怎么做?可能需要JavaScript(Ajax技术)

1 个答案:

答案 0 :(得分:0)

使用ajax你可以这样做, 改变你的选择如下

 <%= f.select(:course_id, @courses.map{|p| [p.id]},{},{:class => "course_id"}) %>

年:

 <%= f.select(:year_id, @years.map{|p| [p.name, p.id]} ,{},{:onchange => "update_student(this.value)"}) %>

文本框:

<%= f.text_field :count_stud, :value => @student_count,:class => "student" %>
在ajax代码中

function update_student(year) {  
 var course = jQuery(".course_id").val(); // finding course value
 if(course == ""){                        // checking course value being selected or not
   alert("Please select course ");
   return false;
 }
 jQuery.ajax({
 url: "update_student",
 type: "GET",
 data: {"course_id" : course,"year": year },
 dataType: "text",
 success: function(data) {
 jQuery(".student").val(data); // inserting response to text field.
 }
 });
}

所以,onchange课程选择框中的一个ajax请求将带有年份和课程值,然后在您的操作中,您获得params中的值并找到no of student并返回喜欢 在YearCoursesController

   def update_student
      year = params[:year]
      course = params[:course]
      #write logic to find student
      #assign in one variable 
      year_courses = YearCourse.find_by(year_id: year, course_id: course)
      student_count = year_courses ? year_courses.students.count : 0
      render :text => student_count  #we are returning the value
   end

然后该值将插入文本框。