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.
24 lines
435 B
Ruby
24 lines
435 B
Ruby
class SDG::Target < ApplicationRecord
|
|
include SDG::Related
|
|
|
|
validates :code, presence: true, uniqueness: true
|
|
validates :goal, presence: true
|
|
|
|
belongs_to :goal
|
|
has_many :local_targets, dependent: :destroy
|
|
|
|
def title
|
|
I18n.t("sdg.goals.goal_#{goal.code}.targets.target_#{code_key}.title")
|
|
end
|
|
|
|
def self.[](code)
|
|
find_by!(code: code)
|
|
end
|
|
|
|
private
|
|
|
|
def code_key
|
|
code.gsub(".", "_").upcase
|
|
end
|
|
end
|