我非常不了解Ruby。我的一个疑问是,如何从视图调用控制器方法。
我的控制器
def course_user_count
@courses=Course.all
@courses.each do |course|
@count=course.students.count
end
我需要在我的视图course.view.html.erb中从方法中调用@count变量。
我非常不了解Ruby。我的一个疑问是,如何从视图调用控制器方法。
我的控制器
def course_user_count
@courses=Course.all
@courses.each do |course|
@count=course.students.count
end
在你的控制器顶部,你可以将你希望在视图中使用的方法标记为辅助方法:
helper_method :course_user_count
那么在您的视图中,您可以调用course_user_count并存储结果。
<% count = course_user_count %>
helper_method :course_user_count
。 - Sri Harsha Kappala当你说在视图中“调用这个@count
变量”时,我不太明白你的意思。你没有在控制器中设置该变量吗?如果是这样,它应该自动可在相关视图中访问。(你不会“调用”一个变量,而是读取或设置它。)
其次,你的方法读取每门课程的学生人数,然后将其赋值给变量@count
。每次写入此变量时,都会覆盖其先前的值,因此按照现有方式编写的方法是无用的。我不确定你想在这里做什么——也许是通过提前为每门课程设置此值来“初始化”控制器?
按照惯例,控制器的show
方法显示相关数据库的一行信息。如果目的是在该视图中显示课程的学生人数,我会在app/controllers/course_controller.rb
中编写如下内容:
class CourseController < ApplicationController
def show
@course = Course.find(params[:id]) # Here I assume that the url is .../courses/<id>
@student_count = @course.students.count
end
...
end
app/views/courses/show.html.erb
:<%= @student_count %>
class CourseController < ApplicationController
helper_method :total_student_count
def total_student_count
total_count = 0
Course.all.each do |c|
total_count += c.students.count
end
total_count
end
...
end
在app/views/courses/
下的任何模板中使用以下方法,以显示该方法返回的值:
<%= total_student_count %>
<% count = course_user_count %>
你可以通过变量在视图中访问你的控制器:
@controller
这是默认提供的。当然,我指的是与该特定视图相关联的控制器。
在您的情况下:
@controller.course_user_count