Module: Slugs::ActiveRecord::Translatable::ClassMethods

Defined in:
lib/slugs/active_record/translatable.rb

Instance Method Summary collapse

Instance Method Details

#exists_by_slug?(id) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
44
# File 'lib/slugs/active_record/translatable.rb', line 41

def exists_by_slug?(id)
  t = reflect_on_association(:translations)
  joins(:translations).exists? t.table_name.to_sym => { slug: id, locale: I18n.locale }
end

#find_by_slug(id) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/slugs/active_record/translatable.rb', line 32

def find_by_slug(id)
  t = reflect_on_association(:translations)
  joins(
    "INNER JOIN #{t.table_name} t ON t.#{t.foreign_key} = #{table_name}.#{t.active_record_primary_key}"
  ).where(
    "t.slug = ? AND t.locale = ?", id, I18n.locale
  ).readonly(false).first
end

#find_previous_slug(slug) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/slugs/active_record/translatable.rb', line 21

def find_previous_slug(slug)
  t = reflect_on_association(:translations)
  joins(
    "INNER JOIN #{t.table_name} t ON t.#{t.foreign_key} = #{table_name}.#{t.active_record_primary_key}"
  ).where(
    "(t.slug LIKE ? OR t.slug = ?) AND t.locale = ?", "#{slug}-%", slug, I18n.locale
  ).order(
    'LENGTH(t.slug) DESC, t.slug DESC'
  ).map(&:slug).select{ |r| r =~ /^#{slug}(-\d+)?$/ }.first
end