Rails 3 how to add a custom method to a controller

I use http://guides.rubyonrails.org/getting_started.html as an example to help me create my own application. I create a blog and comment modules are just fine. When I add a method to comments or block controllers, I cannot get the link_to action to work with calling a new function. Everything indicates a problem in route.rb, but I tried all the new syntax that I saw and nothing works for me.

I am trying to create a simple execution method in a controller to run a ruby ​​script and store the output in a database. Everything works according to the tutorial, but when I try to extend the comment controller with a special function called execute, I cannot start it.

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" 
+3
source share
1 answer

run rake routes and check if there are any routes that indicate the action of your controller. If not, you need to create it either as a "member action" or using a matching rule.

If you see a route, you can name it by passing the parameter: as => route_name to the routing rule. This will allow the use of the route_name_path () and route_name_url () attributes for your link_to

RailsCasts has a good rails 3 routing syntax brief here

EDIT:

based on code examples, try the following:

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

According to the docs here, the parameter :method can only contain valid http verbs (get, put, post, delete). The link_to helper cannot decide which action you want to hit with the custom action of the element, so you need to use a named route as described above.

NTN

+5
source

Source: https://habr.com/ru/post/1396953/


All Articles