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]
修复方案
问题根源
- 路由参数匹配混乱:
quote_download_url生成路由时,Rails会默认把第一个参数识别为:id,但你未显式传递:locale参数,导致Rails错误地将@quote.token赋值给了:locale,同时缺失了必填的:id参数。 - 模板语法错误:邮件模板第一行的
Dear <= @client.name %>存在语法错误,正确写法应为<%= @client.name %>。
具体修复步骤
- 修正模板语法错误:将邮件模板第一行的错误语法改为标准ERB输出格式:
Dear <%= @client.name %> - 显式传递所有路由参数:修改链接生成代码,明确指定每个路由参数,避免Rails自动匹配出错:
<%= quote_download_url(id: @quote.token, namespace: @account.namespace, locale: @quote.locale) %> - 可选优化:自定义路由参数名:如果希望用
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
相关产品推荐
相关产品推荐

