1

我在多语言 Rails 应用程序中配置了 I18n、Globalize 和 FriendlyId。此外,我假装根据语言环境翻译 url。

例如:

http://localhost:3000/es/micontroller/mi-casa   
http://localhost:3000/en/mycontroller/my-house  

这些网址已经存在,翻译按预期工作。

这些是我添加的语言切换器链接:

= link_to_unless I18n.locale == :es, "Español", locale: :es  
= link_to_unless I18n.locale == :en, "English", locale: :en

我的问题是,当我切换语言时,url 只会更改 locale 参数,而不是更改 slug。

例如,从英语切换到西班牙语会产生如下结果:

http://localhost:3000/es/mycontroller/my-house

PD:我假装对我的网址做的事情是一种好习惯吗?我已经搜索了一段时间没有结果。

4

1 回答 1

1

你没有提供你的问题的完整规格,所以我想出了我自己的实现。

通过这个 gem 的额外帮助,我已经成功地完成了你所期望的事情: https ://github.com/norman/friendly_id-globalize

它还翻译friendly_id 所需的slug 列。没有它,slug 直接取自主模型,而不是翻译。

我的设置中的几个片段(我使用 Post 作为我的模型/脚手架):

# model
class Post < ActiveRecord::Base
  extend FriendlyId
  translates :title, :body, :slug
  friendly_id :title, use: :globalize
end

# routes
scope "/:locale", locale: /#{I18n.available_locales.join("|")}/ do
  resources :posts
end

# migration
class CreatePosts < ActiveRecord::Migration
  def up
    create_table :posts do |t|
      t.string :slug 
      # slug column needs to be both in normal and translations table
      # according to friendly_id-globalize docs
      t.timestamps null: false
    end

    Post.create_translation_table! title: :string, body: :text, slug: :string
  end

  def down
    drop_table :posts
    Post.drop_translation_table!
  end
end


# switcher in view
<%= link_to_unless I18n.locale == :en, "English", locale: :en %>
<%= link_to_unless I18n.locale == :es, "Español", locale: :es %>

我希望这将有所帮助。如果不是,请提供更多详细信息。

于 2015-04-27T14:02:44.227 回答