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

Rails with_locale方法无法兼容额外URL参数?如何修复路由错误?

问题:Rails 7邮件生成下载链接时路由匹配失败

相关代码

1. QuoteMailer 实现

# app/mailers/quote_mailer.rb

class QuoteMailer < ApplicationMailer

  def quote_mail(quote)
    @quote = quote
    @user = quote.user
    @client = quote.client
    @account = quote.account
    I18n.with_locale(@quote.locale) do
      mail(
        :from     => @user.email,
        :to       => @client.email,
        :subject  => "New Quote"
      )
    end
  end

end

2. 邮件文本模板

# app/views/mailer/quote_mail.text.erb

Dear <%= @client.name %>

Please click here to download your Quote:

<%= quote_download_url(@quote.token, :namespace => @account.namespace) %>

Best regards

<%= @user.name %>

3. 路由配置

# config/routes.rb

Rails.application.routes.draw do

  scope ':locale', :locale => /#{I18n.available_locales.join("|")}/ do

    scope ':namespace' do

      resources :quote_downloads, :only => [:show]

    end

  end

end

报错信息

ActionView::Template::Error (No route matches {:action=>"show",
:controller=>"quote_downloads",
:locale=>"VmKHoRSx79AEatcoHtPz8uun", :namespace=>"volkswagen"}, missing
required keys: [:id], possible unmatched constraints: [:locale]

修复方案

问题根源

  1. 路由参数匹配混乱:quote_download_url 生成路由时,Rails会默认把第一个参数识别为:id,但你未显式传递:locale参数,导致Rails错误地将@quote.token赋值给了:locale,同时缺失了必填的:id参数。
  2. 模板语法错误:邮件模板第一行的Dear <= @client.name %>存在语法错误,正确写法应为<%= @client.name %>。

具体修复步骤

  1. 修正模板语法错误:将邮件模板第一行的错误语法改为标准ERB输出格式:
    Dear <%= @client.name %>
    
  2. 显式传递所有路由参数:修改链接生成代码,明确指定每个路由参数,避免Rails自动匹配出错:
    <%= quote_download_url(id: @quote.token, namespace: @account.namespace, locale: @quote.locale) %>
    
  3. 可选优化:自定义路由参数名:如果希望用token代替默认的id作为路由参数,可以修改路由配置,让语义更清晰:
    # config/routes.rb
    Rails.application.routes.draw do
      scope ':locale', locale: /#{I18n.available_locales.join("|")}/ do
        scope ':namespace' do
          resources :quote_downloads, only: [:show], param: :token
        end
      end
    end
    
    对应模板链接修改为:
    <%= quote_download_url(token: @quote.token, namespace: @account.namespace, locale: @quote.locale) %>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:28:38