【问题标题】:Rails 3 how to add a custom method to controllerRails 3如何向控制器添加自定义方法
【发布时间】:2010-12-15 07:18:59
【问题描述】:

我以http://guides.rubyonrails.org/getting_started.html 为例来帮助我创建自己的应用程序。我创建博客和 cmets 模块就好了。当我向 cmets 或博客控制器添加方法时,我无法让 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"

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

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

    如果您确实看到了路由,您可以通过将 :as => 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

    【讨论】:

    • 谢谢,我看过 rails casts 并且学到了很多东西。我能够获得一个与 Post 控制器一起使用的新功能,但仍然无法让它与 Comments 控制器一起运行。我更新了问题以包含我正在使用的代码。
    • 链接也很棒!刚才真的很有帮助!
    • 链接的视频不再可用,没有这个答案不能提供问题的完整解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2011-07-07
    • 2019-01-25
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多