diff --git a/app/models/discourse_data_explorer/query.rb b/app/models/discourse_data_explorer/query.rb index b5e0dcc..c3316bc 100644 --- a/app/models/discourse_data_explorer/query.rb +++ b/app/models/discourse_data_explorer/query.rb @@ -1,6 +1,18 @@ # frozen_string_literal: true module ::DiscourseDataExplorer + class QueryFinder + def self.find(id) + default_query = Queries.default[id.to_s] + return raise ActiveRecord::RecordNotFound unless default_query + + query = Query.find_by(id: id) || Query.new + query.attributes = default_query + query.user_id = Discourse::SYSTEM_USER_ID.to_s + query + end + end + class Query < ActiveRecord::Base self.table_name = "data_explorer_queries" @@ -35,15 +47,17 @@ module ::DiscourseDataExplorer end def self.find(id) - if id.to_i < 0 - default_query = Queries.default[id.to_s] - return raise ActiveRecord::RecordNotFound unless default_query - query = Query.find_by(id: id) || Query.new - query.attributes = default_query - query.user_id = Discourse::SYSTEM_USER_ID.to_s - query - else - super + return super if id.to_i >= 0 + QueryFinder.find(id) + end + + private + + # for `Query.unscoped.find` + class ActiveRecord_Relation + def find(id) + return super if id.to_i >= 0 + QueryFinder.find(id) end end end diff --git a/spec/models/query_spec.rb b/spec/models/query_spec.rb new file mode 100644 index 0000000..e3c0203 --- /dev/null +++ b/spec/models/query_spec.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +RSpec.describe DiscourseDataExplorer::Query do + before { SiteSetting.data_explorer_enabled = true } + + describe ".find" do + it "returns default queries" do + expect(DiscourseDataExplorer::Query.find(-1)).to be_present + end + end + + describe "unscoped .find" do + it "returns default queries" do + expect(DiscourseDataExplorer::Query.unscoped.find(-1)).to be_present + end + end +end