0

I am using FriendlyId across a bunch of different model. For a particular use-case with usernames, I can't use FriendlyId but still want to make sure the username is not being used as a slug in any of those models.

Currently, I have a .exists query for each model using FriendlyId. It doesn't feel super efficient, so I am wondering if there is a more efficient way of doing this by just querying the slugs column in friendly_id_slugs table that the library creates?

I'm on Rails 5.1, Postgres 9.5.x and FriendlyId 5.2.3

halfer
  • 19,824
  • 17
  • 99
  • 186
geoboy
  • 1,172
  • 1
  • 11
  • 25

2 Answers2

2

The answer by @Ben helped me find the ideal solution. It turns out that FriendlyId has an internal model - FriendlyId::Slug, that is backed by the friendly_id_slugs table.

So, a query like the following worked for me:

FriendlyId::Slug.where(
    sluggable_type: ["Animals", "Plants"]
  )
  .where('lower(slug) = ?', potential_username.downcase)
  .exists?
halfer
  • 19,824
  • 17
  • 99
  • 186
geoboy
  • 1,172
  • 1
  • 11
  • 25
1

Defining a model map it to its table, simply create a app/models/friendly_id_slug.rb file, containing :

class FriendlyIdSlug < ApplicationRecord
end

You then get a standard model active record querying methods (FriendlyIdSlug.where…)

Alertnatively, running raw sql would apply :

ActiveRecord::Base.connection.execute("select * from friendly_id_slugs etc…")

That is, your .exists? sounds fair too. If you repeat code for each model, you could make a app/models/concerns or app/lib class file you'd reuse in the concerned models

Ben
  • 5,030
  • 6
  • 53
  • 94
  • Thanks Ben! The first option seems smart, and the cleanest. Do you see any side-effects of declaring a model where one wasn't declared by the library (other than library doing that in a future version)? – geoboy Mar 03 '18 at 21:21
  • With the `.exists?` option, I wasn't sure if that was also gonna be the most performant - one query in your solutions vs 5-6 with `exists`? – geoboy Mar 03 '18 at 21:21
  • well you found out how; wasn't aware of this one; super-clean then! – Ben Mar 03 '18 at 21:50