Rails 3如何向控制器添加自定义方法

时间:2010-12-15 07:18:59

标签: ruby-on-rails-3

我使用http://guides.rubyonrails.org/getting_started.html作为示例来帮助我创建自己的应用程序。我很好地创建了博客和评论模块。当我向评论或博客控制器添加方法时,我无法获得link_to操作来调用新函数。所有的东西都指向routes.rb中的一个问题,但我已经尝试了所有我见过的新语法,没有什么对我有用。

我要做的是在控制器中创建一个简单的执行方法来运行ruby脚本并将输出保存到数据库。一切都按照教程工作,但当我尝试使用名为execute的自定义函数扩展注释控制器时,我无法运行。

comments_controller.rb  #Same as destroy 
def execute
  @post = Post.find(params[:post_id])
  @comment = @post.comments.find(params[:id])
  @comment.destroy
  redirect_to post_path(@post)
 end

_comment.html.erb
<%= link_to 'Execute Comment', [comment.post, comment],
    :method => :execute %>

routes.rb
resources :posts do
  resources :comments do
    get :execute, :on => :member
  end
end

rake routes |grep execute
execute_post_comment GET    /posts/:post_id/comments/:id/execute(.:format) {:action=>"execute", :controller=>"comments"}

Error when I click Execute comment link:
No route matches "/posts/3/comments/6"

1 个答案:

答案 0 :(得分:5)

运行rake routes并查看是否有任何路由指向您的控制器操作。如果不是,您需要创建一个作为“成员操作”或匹配规则。

如果您确实看到了路线,可以通过传递:as =&gt;来命名。 route_name参数到路由规则。这样做会为link_to启用route_name_path()和route_name_url()助手

RailsCasts有一个很好的快速概述rails 3路由语法here

编辑:

基于代码示例,试试这个:

<%= link_to 'Execute Comment', execute_post_comment_path(comment.post, comment) %>

根据文档here:method选项只能包含有效的http动词(get,put,post,delete)。 link_to帮助程序无法解决您想要使用自定义成员操作执行的操作,因此您必须使用上面命名的路由。

HTH