Reputation: 53
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..
Upvotes: 1
Views: 51
Reputation: 53038
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
Upvotes: 2