gpt4 book ai didi

javascript - 路由到 Controller 中的自定义操作

转载 作者:行者123 更新时间:2023-11-30 17:29:23 24 4
gpt4 key购买 nike

我正在尝试添加将在单击 div 时呈现部分内容的 ajax。

这个链接:

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

我在视频 Controller 中有自定义方法:

def update_comments
puts "hello"
end

路线是这样的:

get 'videos/update_comments'

但是,我得到这个错误:

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'

我按照一堆堆栈溢出问题让我做的,但它仍然不起作用..

最佳答案

get 'videos/update_comments' 移动到为 videos 资源定义的 show 路由之上。

例如:

get 'videos/update_comments'
resources :videos

目前,当您对 videos/update_comments 发出 GET 请求时,Rails 会从 routes.rb 中找到第一个匹配项并将请求路由到那里。因此,它匹配 videos/:id 路由并将请求路由到 VideosController#show 操作而不是 VideosController#update_comments

在生成的日志中可以看得很清楚

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

通过将 update_comments 路由移动到 show 路由之前,每当对 videos/update_comments 发出 GET 请求时,第一个匹配将是 在你的 route 获取'videos/update_comments',请求将被定向到VideosController#update_comments

更新

您还可以按照 @Addicted 在评论中的建议,在 collection 中定义 update_comments 路由,前提是您已经定义了使用的路由资源:视频

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

关于javascript - 路由到 Controller 中的自定义操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23478660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com