You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 5:按钮触发控制器方法的路由配置问题求助

解决Rails自定义控制器方法的路由匹配问题

这个问题我之前也碰到过,核心原因很简单:你用的resources :imagecapturings只会生成标准的RESTful路由(比如index、show这些),自定义的digitized_in_stgallen方法并没有被注册到路由里,所以才会出现"No route matches"的错误。下面一步步来修复:

1. 配置自定义路由

打开config/routes.rb,在resources :imagecapturings内部添加一个collection路由(因为你的方法是查询一批记录,不需要单个资源的ID):

Rails.application.routes.draw do
  resources :imagecapturings do
    collection do
      get 'digitized_in_stgallen' # 用GET请求符合查询操作的语义
    end
  end
end

你可以在终端跑rails routes命令确认,会看到新增的路由:

digitized_in_stgallen_imagecapturings GET    /imagecapturings/digitized_in_stgallen(.:format) imagecapturings#digitized_in_stgallen

2. 修改视图中的按钮

button_to默认会发送POST请求,但我们路由定义的是GET,所以要显式指定请求方法,同时使用生成的路由辅助方法:

<%= button_to "St. Gallen", digitized_in_stgallen_imagecapturings_path, method: :get %>

3. 优化控制器方法

把SQL查询改成更简洁安全的Rails风格写法,同时记得渲染index视图(不然Rails会去找不存在的digitized_in_stgallen.html.erb视图):

def digitized_in_stgallen
  # 用哈希语法替代字符串SQL,更安全易读
  @imagecapturings = Imagecapturing.where(digitalisiert_in: 'St. Gallen')
  # 复用index视图展示过滤后的结果
  render :index
end

这样点击按钮后,就会触发digitized_in_stgallen方法,过滤出符合条件的记录,然后用原来的index视图展示啦。

内容的提问来源于stack exchange,提问作者Trinity76

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:17:38