有一种形式可以让我们选择年份和课程。另一个字段不可见(它应更改学生数量,它对应于所选课程).Сhose使用f.select的课程,并自动输入字段count_stud值等于此课程的学生数量。该怎么做呢?可能需要JavaScript (Ajax技术)
发布于 2014-04-29 23:47:40
使用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然后,该值将插入到文本框中。
https://stackoverflow.com/questions/23368828
复制相似问题