Search code examples
ruby-on-railsfriendly-idglobalize

Friendly_id and globalize - use default translation for slug if translation is missing


I have integrated friendly_id gem and globalize and it works just fine if I have translation for slug in specific locale.

But what I want to achieve is to use default translation for slug in case it is missing in translation table for some locale.

So let say I have a master locale MA where the slug is filled and I have a EN locale, where it is missing. If I will go to EN version, I want to see MA version of the slug.

Is there a way how to do this?

Thanks, Miroslav


Solution

  • I figured this out finally by writing an application helper method (other solutions did not work for me). Hope it will help someone. If the translations do not exist for a product, it will use master translation (which is created by default on product creation) otherwise use current locale version.

    # application_helper.rb
    
    def product_url(product)
        if product.translations.pluck(:locale).include?(I18n.locale.to_s)
          admin_translations_product_path(product)
        else
          I18n.with_locale(:ma) { admin_translations_product_path(product) }
        end
    end
    
    # index.html.erb
    <%= link_to "#{t :button_admin_edit} #{locale.to_s.upcase}", product_url(product) %>