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

Chose a course using f.select and automatically entered into the field count_stud value

本文关键字:count 输入 stud 字段 select 选择 使用      更新时间:2023-09-26

我们可以通过表格选择年份和课程。另一个字段不可见(它应该改变与所选课程相对应的学生人数)。С使用f.select选择一门课程,并自动输入字段count_stud值,该值等于该课程的学生人数。如何做到这一点?可能需要JavaScript(Ajax技术)

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

则该值将插入到文本框中。