4

i'm currently working on a project which has 2 different locals (nl/fr).

We're facing this problem : How can I get the translated url for the current page when I display fr/nl button

I'm currently working with friendly_id and globalize

we've tried :

= link_to "nl", params.merge(locale: "nl")
= link_to "nl", url_for(:locale => :nl)

both work to change the current language but as we've friendly_url, when the page is loaded in french (localhost:3000/c/animaux)

we should have

localhost:3000/nl/c/dieren

instead of

localhost:3000/nl/c/animaux 

I've so many link to translate so I wish there's a railsway to do this.

Thounder
  • 315
  • 2
  • 14
  • Is "animaux" stored in slug column and coming from your database? – Surya May 29 '15 at 07:58
  • Sorry, I did not read the question carefully enough, it's not a duplicate. – max May 29 '15 at 08:00
  • yes it's stored in the database with globalize : **Table category :** `name_fr : animaux` | `name_nl : dieren` – Thounder May 29 '15 at 08:01
  • @Thounder : So do you store copy of friendly url in each locale? `name_fr` and `name_nl`? If so, is it the same table or db? And do you follow the same pattern for all such columns? for example `description_fr` and `description_nl`? – Surya May 29 '15 at 08:03
  • @Surya I'm using globalize gem so I call `category.name` and based on the current local I receive `category.name_fr` or `category.name_nl` . The fact is that when I put the link `localhost:3000/c/animaux, local=>nl` the current local still "fr" – Thounder May 29 '15 at 08:28

1 Answers1

1

You could either pass the resource to url_for:

= link_to "nl", params.merge(locale: "nl", id: @resource.id)

If that is too much code duplication you could create a helper:

# Try to guess the resource from controller name
# @param [String] locale
# @param [Hash] options - passed on to url_for
#   @option options [String] :text the text for the link
#   @option options [Object] :resource the model to link to.
def page_in_other_locale(locale, options = {})
  opts = params.dup.merge(options).merge(locale: locale)
  text = opts[:text] || locale     
  resource = nil

  if opts[:resource] 
    resource = opts[:resource]
  else
    resource = controller.instance_variable_get?(":@#{controller_name.singularize}")
  end

  opts.merge!(id: resource.try(:id)) if resource
  link_to(text, opts.except(:text, :resource))
end

Another alternative is to use I18n.with_locale, it lets you run a block in another locale:

I18n.with_locale(:nl) do
  link_to('nl', params.merge(id: category.name))
end
max
  • 96,212
  • 14
  • 104
  • 165
  • Well, thanks for your answer, you get me a part of the solution and I'll figure out the rest on myself. `= link_to "nl", params.merge(locale: "nl", id: @resource.id)` – Thounder May 29 '15 at 09:16