1
votes

I have configured I18n, Globalize and FriendlyId in a Multilingual Rails Application. Moreover, I pretend to translate url according locale.

For example:

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

Those urls already exists, the translation works as expected.

These are the language switcher links I have added:

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

My issue is that when I switch languages, the url only changes the locale parameter, instead of changing slug.

For example, toggling from English to Spanish results in something like:

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

PD: Is a good practice what I pretend to do with my urls? I have searched some time with no results.

1

1 Answers

1
votes

You didn't provide full specs of your problem, so I came up with implementation of my own.

I've managed to accomplish kind of what you expect with addtional help of this gem: https://github.com/norman/friendly_id-globalize

It also translates the slug column needed by the friendly_id. Without it, slug was taken directly from main model, not from translation.

Few snippets from my setup (I used Post as my model/scaffold):

# 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 %>

I hope this will help. If not, please provide more details.