我正在开发 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
答案 0 :(得分:23)
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
答案 1 :(得分:2)
您可以在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
这是未经测试但应该有效。如果您还有其他问题,请发表评论。