locale.rb 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class KnowledgeBase::Locale < ApplicationModel
  3. belongs_to :knowledge_base, inverse_of: :kb_locales, touch: true
  4. belongs_to :system_locale, inverse_of: :knowledge_base_locales, class_name: '::Locale'
  5. validates :primary, uniqueness: { case_sensitive: true, scope: %i[system_locale_id knowledge_base_id] }, if: :primary?
  6. validates :system_locale_id, uniqueness: { case_sensitive: true, scope: :knowledge_base_id }
  7. has_many :knowledge_base_translations, class_name: 'KnowledgeBase::Translation',
  8. inverse_of: :kb_locale,
  9. foreign_key: :kb_locale_id,
  10. dependent: :destroy
  11. has_many :category_translations, class_name: 'KnowledgeBase::Category::Translation',
  12. inverse_of: :kb_locale,
  13. foreign_key: :kb_locale_id,
  14. dependent: :destroy
  15. has_many :answer_translations, class_name: 'KnowledgeBase::Answer::Translation',
  16. inverse_of: :kb_locale,
  17. foreign_key: :kb_locale_id,
  18. dependent: :destroy
  19. has_many :menu_items, class_name: 'KnowledgeBase::MenuItem',
  20. inverse_of: :kb_locale,
  21. foreign_key: :kb_locale_id,
  22. dependent: :destroy
  23. def self.system_with_kb_locales(knowledge_base)
  24. ::Locale
  25. .joins(:knowledge_base_locales)
  26. .where(knowledge_base_locales: { knowledge_base: knowledge_base })
  27. .select('locales.*, knowledge_base_locales.id as kb_locale_id, knowledge_base_locales.primary as primary_locale')
  28. end
  29. def self.preferred(user, knowledge_base)
  30. preferred_via_system(user, knowledge_base) ||
  31. preferred_via_kb(user, knowledge_base) ||
  32. knowledge_base.kb_locales.first
  33. end
  34. def self.preferred_via_system(user, knowledge_base)
  35. knowledge_base
  36. .kb_locales
  37. .joins(:system_locale)
  38. .find_by(locales: { locale: user.locale })
  39. end
  40. def self.preferred_via_kb(_user, knowledge_base)
  41. knowledge_base.kb_locales.find_by(primary: true)
  42. end
  43. scope :available_for, ->(object) { where(id: object.translations.select(:kb_locale_id)) }
  44. end