Rails 7.0.6视图中如何引用自定义controller方法的路由路径?
解决Rails自定义member路由的视图引用问题
核心问题分析
你的问题出在两个关键点:
- 自定义member路由的辅助方法名称写错了
- 没有为member路由传入对应的资源实例(member路由针对单个
merchants_file操作,必须携带id参数)
步骤1:确认正确的路由辅助方法名称
在终端运行rails routes命令,查看自定义路由生成的实际辅助方法。针对你的配置,输出会包含类似条目:
load_merchants_file POST /merchants_files/:id/load(.:format) merchants_files#load
这里的load_merchants_file_path就是你需要的路由辅助方法(命名规则:动作名在前,资源名在后)。
另外,你routes配置里的:as => :load是多余的,Rails默认会生成清晰的辅助方法,建议简化路由代码:
Rails.application.routes.draw do resources :merchants_files, except: [:edit] do member do post 'load' end end end
步骤2:修正视图中的路径调用
因为是member路由,必须传入对应的merchants_file实例(或其id)才能生成合法URL。修改视图里的button_to代码:
<%= button_to "Load the merchants file", load_merchants_file_path(@merchants_file), method: :post %>
额外注意:Controller中的资源查找
你的load动作直接使用@merchants_file但未从数据库查找,会触发nil错误。需要添加资源查找逻辑,或通过before_action统一处理:
# merchants_files_controller.rb before_action :set_merchants_file, only: [:show, :destroy, :load] def load CSV.foreach(@merchants_file.merchants_csv, headers: true, col_sep: ";") do |merchant| Merchant.create!(merchant.to_hash) end respond_to do |format| format.html { redirect_to merchants_files_url, notice: "Merchants loaded." } end end private def set_merchants_file @merchants_file = MerchantsFile.find(params[:id]) end
验证方法
修改完成后重启服务器,访问merchants_file的show页面,点击按钮即可正确触发load动作。若仍有路由错误,再次运行rails routes确认辅助方法名称。
内容的提问来源于stack exchange,提问作者Sergey Panov
相关产品推荐
相关产品推荐

