从View执行Controller Action

时间:2009-09-20 14:17:01

标签: ruby-on-rails

我是Ruby on Rails(RoR)的新手。我在控制器上创建了一个新方法。我想从视图中调用新方法。

在我看来,我有这段代码:

<%= link_to "MyMethod", :method=>:MyMethod %>

当我点击链接时,网址会更改为http://localhost:3000/seats?method=MyMethod,页面会在浏览器上重新加载,从日志中我可以看到MyMethod永远不会被执行。

如何从视图中调用方法?

3 个答案:

答案 0 :(得分:0)

Ops ...方法的东西,不是用于调用方法而是用于描述HTTP方法。 好的,所以我不应该使用方法。 如果我使用:action =&gt;“MyMethod”

网址变为 座/的MyMethod

产生错误,找不到id = mymethod的座位 我该如何使其发挥作用?

答案 1 :(得分:0)

这个问题似乎存在于你的路线中(或者你实际上需要一个视图助手,正如ndp建议的那样)。

如果路线更合适,请查看优秀的rails routing guide。我可以想象两种解决方案中的一种:

  • map.resources :the_resource, :member => { :my_method => :get }:如果方法作用于the_resource的一个实例,请使用此方法。该网址最终结果如下:/the_resource/:id/my_method
  • map.resources :the_resource, :collection => { :my_method => :get }:如果出现以下情况,请使用此方法:my_method作用于the_resource的许多实例 - 一个集合。该网址最终为:/the_resource/my_method

然后运行rake routes | grep my_method。您将找到由rails生成的路由助手来访问此方法。你可以通过my_method_the_resource(@an_instance) - 为成员案例调用它们,或者为集合案例调用my_method_the_resources。

有关链接指南第3.11节的更多信息。

答案 2 :(得分:0)

假设'mymethod'位于名为'users'的控制器中,并指向一个动作'mymethod' 在您的routes.rb中添加:

map.my_method'/ mymethod',:controller =&gt; 'users',:action =&gt; '的MyMethod'

然后在您的视图中,您可以这样称呼它: