简体   繁体   中英

Routing to custom action in controller

I'm trying to add ajax that would render a partial upon clicking a div.

This the link:

<h1 id="comments_viewall"><%= link_to "View All", videos_update_comments_path, remote: true%></h1>

I have the custom method in the videos controller:

def update_comments
    puts "hello"
end

And the routes are as such:

get 'videos/update_comments'

However, I get this error:

GET http://localhost:3000/videos/update_comments 404 (Not Found) 

Started GET "/videos/update_comments" for 127.0.0.1 at 2014-05-05 13:49:02 -0400
Processing by VideosController#show as JS
  Parameters: {"id"=>"update_comments"}
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
 in show
  Video Load (0.1ms)  SELECT "videos".* FROM "videos" WHERE "videos"."id" = ? LIMIT 1  [["id", "update_comments"]]
 Completed 404 Not Found in 2ms

ActiveRecord::RecordNotFound (Couldn't find Video with id=update_comments):
  app/controllers/videos_controller.rb:94:in `show'

I followed what bunch of stack overflow questions told me to do, but its still not working..

Move get 'videos/update_comments' above the show route defined for videos resource.

For example:

get 'videos/update_comments'
resources :videos

As currently, when you do a GET request for videos/update_comments , Rails finds the first match from routes.rb and routes the request there. So, it matches videos/:id route and routes the request to VideosController#show action instead of VideosController#update_comments .

You can see it clearly in the generated log

Started GET "/videos/update_comments" for 127.0.0.1 at 2014-05-05 13:49:02 -0400
Processing by VideosController#show as JS

By moving the update_comments route before show route, whenever a GET request for videos/update_comments is made, the first match would be get 'videos/update_comments' in your routes and the request would be directed to VideosController#update_comments

UPDATE

You could also define the update_comments route within a collection as suggested by @Addicted in the comments provided that you have defined the routes using resources :videos

  resources :videos do
    collection do
      get 'update_comments'
    end
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM