Ruby-on-rails link_to 路径定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8477301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:29:09  来源:igfitidea点击:

link_to path definition

ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

提问by Mellon

I am developoing a Rails v2.3.2app.

我正在开发一个Rails v2.3.2应用程序。

I have a controller:

我有一个控制器:

class SchoolController < ApplicationController
  ...

  def edit
    @school=School.find_by_id params[:id]

  end

  def check_teachers
    @teachers = @school.teachers
    ...
  end

end

in app/views/schools/edit.html.erbI would like to have a link, click on it will trigger the check_teachersmethod in the controller, how to define the pathfor this link?

app/views/schools/edit.html.erb我想有一个link,点击它会触发check_teachers该方法控制器,如何定义路径为这个link

app/views/schools/edit.html.erb :

app/views/schools/edit.html.erb :

link_to 'Check teachers' WHAT_IS_THE_PATH_HERE

回答by rubyprince

link_to 'Check teachers', :action => :check_teachers, :id => @school.id

or

或者

link_to 'Check teachers', "/school/check_teachers/#{@school.id}"

or you can define a named-route in config/routes.rblike this:

或者你可以config/routes.rb像这样定义一个命名路由:

map.check_teachers, '/school/check_teachers/:id' :controller => :school, :action => :check_teachers

and call the url-helper generated by the named-route like this:

并像这样调用由命名路由生成的 url-helper:

link_to 'Check teachers', check_teachers_path(:id => @school.id)

and you can use this id to find teachers in the controller

您可以使用此 ID 在控制器中查找教师

def check_teachers
  @school = School.find params[:id]
  @teachers = @school.teachers
  ...
end

回答by Chuck Callebs

You can define something like this in your routes.rbfile.

您可以在routes.rb文件中定义类似的内容。

map.connect "schools/:id/check_teachers", :controller => "schools", :action => "check_teachers"

You'd then set up your link_toas follows:

然后,您link_to将按如下方式设置:

link_to "Check teachers", check_teachers_path(:id => @school.id)

You'll need to add this bit of code into the controller, as model states aren't shared between controller actions:

您需要将这段代码添加到控制器中,因为模型状态不会在控制器操作之间共享:

 def check_teachers
    @school = School.find_by_id(params[:id])
    # Then you can access the teachers with @school.teachers
  end

This is untested but should work. Just comment if you have any further issues.

这是未经测试的,但应该可以工作。如果您有任何进一步的问题,请发表评论。