We noticed there was a performance issue while browsing the SDG Management section and when one of our tests started failing sometimes because the request to the relations#index controller took too long. The issue proved to be `SDG::Target#<=>`. This method calls `.goal` for each target, meaning we were generating 169 database queries when sorting all targets. So we're comparing codes directly to minimize the number of database queries and improve performance. Requests to the relations index take now less than third of the time they used to take.
31 lines
672 B
Ruby
31 lines
672 B
Ruby
class SDG::LocalTarget < ApplicationRecord
|
|
include SDG::Related
|
|
|
|
translates :title, touch: true
|
|
translates :description, touch: true
|
|
include Globalizable
|
|
|
|
validates_translation :title, presence: true
|
|
validates_translation :description, presence: true
|
|
|
|
validates :code, presence: true, uniqueness: true,
|
|
format: ->(local_target) { /\A#{local_target.target&.code}\.\d+/ }
|
|
validates :target, presence: true
|
|
validates :goal, presence: true
|
|
|
|
belongs_to :target
|
|
belongs_to :goal
|
|
|
|
before_validation :set_related_goal
|
|
|
|
def self.[](code)
|
|
find_by!(code: code)
|
|
end
|
|
|
|
private
|
|
|
|
def set_related_goal
|
|
self.goal ||= target&.goal
|
|
end
|
|
end
|