我正在开发一个Rails v2.3.2应用程序。
我有一个控制器:
class SchoolController < ApplicationController
...
def edit
@school=School.find_by_id params[:id]
end
def check_teachers
@teachers = @school.teachers
...
end
end
在app/views/schools/edit.html.erb
我想有一个link
,点击它会触发控制器中的check_teachers
方法,如何定义这个link
的路径?
app / views / schools / edit.html.erb:
link_to 'Check teachers' WHAT_IS_THE_PATH_HERE
link_to 'Check teachers', :action => :check_teachers, :id => @school.id
要么
link_to 'Check teachers', "/school/check_teachers/#{@school.id}"
或者您可以在config/routes.rb
中定义命名路线,如下所示:
map.check_teachers, '/school/check_teachers/:id' :controller => :school, :action => :check_teachers
并调用named-route生成的url-helper,如下所示:
link_to 'Check teachers', check_teachers_path(:id => @school.id)
并且您可以使用此ID在控制器中查找教师
def check_teachers
@school = School.find params[:id]
@teachers = @school.teachers
...
end
您可以在routes.rb
文件中定义类似的内容。
map.connect "schools/:id/check_teachers", :controller => "schools", :action => "check_teachers"
然后你将如下设置你的link_to
:
link_to "Check teachers", check_teachers_path(:id => @school.id)
您需要将此位代码添加到控制器中,因为控制器操作之间不共享模型状态:
def check_teachers
@school = School.find_by_id(params[:id])
# Then you can access the teachers with @school.teachers
end
这是未经测试但应该有效。如果您有任何进一步的问题,请评论。