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

使用Sitemap Generator+Mobility生成多语言站点地图时俄语链接异常求助

多语言站点地图生成问题:俄语路径未使用翻译后的slug

问题描述

使用Sitemap Generator gem结合Mobility和friendly_id构建多语言站点地图时,乌克兰语(:uk)版本的站点地图生成正常,但俄语(:ru)版本的文章、服务链接仍显示乌克兰语slug路径,导致谷歌无法抓取俄语版本的内容。已确认单独生成链接时,俄语slug能输出正确路径。

原代码

SitemapGenerator::Sitemap.default_host = "MY_HOST_NAME"
SitemapGenerator::Sitemap.create_index = true

SitemapGenerator::Sitemap.create do
  {uk: :ukrainian, ru: :russian}.each_pair do |locale, name|
    group(sitemaps_path: "sitemaps/#{locale}/", filename: name) do
      add root_path(locale: locale), changefreq: 'daily'
      add prices_path(locale: locale)
      add about_path(locale: locale)
      add contacts_path(locale: locale)
      add faq_path(locale: locale)
      add services_path(locale: locale)
      add articles_path(locale: locale)

      Article.friendly.find_each do |article|
        add article_path(article, locale: locale), changefreq: 'daily', lastmod: article.updated_at
      end
      Service.friendly.find_each do |service|
        add service_path(service, locale: locale), changefreq: 'daily', lastmod: service.updated_at
      end 
    end
  end
end

问题原因

Mobility依赖当前的I18n.locale来加载对应语言的字段值,原代码仅在路由参数中传入locale,但未切换全局I18n上下文,导致friendly_id生成slug时始终使用默认locale(乌克兰语)的数值,而非当前循环的俄语locale。

解决方案

在每个locale的处理块中,用I18n.with_locale临时切换语言上下文,确保Mobility加载对应语言的slug:

SitemapGenerator::Sitemap.default_host = "MY_HOST_NAME"
SitemapGenerator::Sitemap.create_index = true

SitemapGenerator::Sitemap.create do
  {uk: :ukrainian, ru: :russian}.each_pair do |locale, name|
    # 临时切换locale,确保Mobility加载对应语言的slug
    I18n.with_locale(locale) do
      group(sitemaps_path: "sitemaps/#{locale}/", filename: name) do
        add root_path(locale: locale), changefreq: 'daily'
        add prices_path(locale: locale)
        add about_path(locale: locale)
        add contacts_path(locale: locale)
        add faq_path(locale: locale)
        add services_path(locale: locale)
        add articles_path(locale: locale)

        Article.friendly.find_each do |article|
          add article_path(article, locale: locale), changefreq: 'daily', lastmod: article.updated_at
        end
        Service.friendly.find_each do |service|
          add service_path(service, locale: locale), changefreq: 'daily', lastmod: service.updated_at
        end 
      end
    end
  end
end

额外验证点

  1. 确认模型已正确配置Mobility的slug字段:
    class Article < ApplicationRecord
      extend Mobility
      translates :slug, type: :string, fallbacks: true
      friendly_id :slug, use: :history
    end
    
  2. 检查数据库中是否存在俄语版本的slug数据,且字段不为空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:57:08