shioyama/friendly_id-mobility

Fallbacks for friendly.find

Rwobbema opened this issue · 6 comments

Hello,

I am having a little problem with the fallback of slugs. For example; when I have a Faq with an English question but without a French question, in French it will fallback to the English slug. That is good. But now when I want to find the Faq by Faq.friendly.find(params[:id]) it can not find the Faq.

Is there a way that the fallbacks will also work with friendly.find?

Regards,

Rémon.

So if I understand correctly, you want to search with fallbacks? This is not something supported in Mobility currently, so (by extension) it is not supported in this gem either (currently).

It's a feature I guess people want, but it's tricky to implement so it would take some time. In any case, if it is something you're interested it would help to have a clearly defined use-case or cases as an issue on Mobility.

If I understand, you want to be able to get (say) a post with an English title "foo" with this query, assuming there is no post with a French title "foo":

I18n.locale = :fr
Post.i18n.find_by(title: "foo")
#=> returns Post with English title "foo" after finding none with French title "foo"

This is not so simple to implement, and can easily cause many bugs, so needs to be through through carefully...

I think that the thing you are describing is what I want but then with FriendlyId.

Is there some kind of way to make this work?

Yes, the point is that if it's not a feature of Mobility, it won't be possible in FriendlyId (with Mobility).

Like I said, it's not so easy to do, but it's something that I've thought about. I can't promise anything and certainly it won't happen for at least a few weeks.

I'm closing this since as I said it's not an issue with this gem.

... I should say, it could be implemented in this gem separate from Mobility but that doesn't seem to me to be the right way to do it.

In any case, thanks for pointing to the need for this. I'll keep it in mind. 😄

Okay, Thank you!

For the record, I am temporarily fixing that problem with the following code:

def set_article

        #####
        # Strategies Search article:

        # 1. By id or friendly on current locale
        begin
          @article = SyBlog::Article.friendly.find(params[:id])
        rescue ActiveRecord::RecordNotFound
          # Ignored
        end

        # 2. By friendly on all available locales
        @article ||= Mobility::Backends::ActiveRecord::KeyValue::StringTranslation.where(
                               translatable_type: SyBlog::Article.name,
                               key: "slug",
                               value: params[:id],
                               locale: I18n.available_locales
                     ).last&.translatable
end