Skip to content

Commit

Permalink
Ensure that PagePile Category records are unique by pileid
Browse files Browse the repository at this point in the history
PagePileApi will update the wiki for a Category record, if it doesn't match what the API returns. To avoid hash collisions on Category records, we need to make sure we only have one record per pileid.
  • Loading branch information
ragesoss committed Jan 10, 2025
1 parent c49844d commit 666317c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
4 changes: 2 additions & 2 deletions app/controllers/categories_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ def update_wiki(wiki)

def add_category(params)
name = ArticleUtils.format_article_title(params[:name])
@category = Category.find_or_create_by(wiki: @wiki, depth: params[:depth],
name:, source: params[:source])
@category = Category.get_or_create(wiki: @wiki, depth: params[:depth],
name:, source: params[:source])
@course.categories << @category
end
end
16 changes: 16 additions & 0 deletions app/models/wiki_content/category.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,22 @@ class Category < ApplicationRecord
less_than_or_equal_to: 3
}

def self.get_or_create(wiki:, name:, depth:, source:)
if source == 'pileid'
get_or_create_by_pileid(wiki:, name:, depth:, source:)
else
find_or_create_by(wiki:, name:, depth:, source:)
end
end

def self.get_or_create_by_pileid(wiki:, name:, depth:, source:)
# For pagepile records, the name should be unique. Depth
# is not applicable, and wiki gets set via PagePileApi if it
# doesn't match.
record = find_by(source:, name:)
return record || create(wiki:, name:, depth:, source:)
end

def self.refresh_categories_for(course, update_service: nil)
# Updating categories only if they were last updated since
# more than a day, or those which are newly created
Expand Down

0 comments on commit 666317c

Please sign in to comment.