From b063db4ba4ba00789f86f3ac3315664490c8d544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=94=A6=E5=BF=83?= <41134017+Lhcfl@users.noreply.github.com> Date: Thu, 15 Aug 2024 20:01:53 +0800 Subject: [PATCH] FIX: Use with_deleted only in topic and post (#308) We used `with_deleted` incorrectly in the code. This method does not exist on `User`, `Badge`, and `Group`. This will cause an error when entering a numeric id in these three parameter input, forcing the user to enter the name/username of these inputs. See https://github.com/discourse/discourse-data-explorer/pull/307#issuecomment-2291017256 --- lib/discourse_data_explorer/parameter.rb | 8 +++++++- spec/lib/parameter_spec.rb | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/discourse_data_explorer/parameter.rb b/lib/discourse_data_explorer/parameter.rb index c02d3a8..b34d4ec 100644 --- a/lib/discourse_data_explorer/parameter.rb +++ b/lib/discourse_data_explorer/parameter.rb @@ -193,7 +193,13 @@ module ::DiscourseDataExplorer if string.gsub(/[ _]/, "") =~ /^-?\d+$/ klass_name = (/^(.*)_id$/.match(type.to_s)[1].classify.to_sym) begin - object = Object.const_get(klass_name).with_deleted.find(string.gsub(/[ _]/, "").to_i) + finder = + if type == :post_id || type == :topic_id + Object.const_get(klass_name).with_deleted + else + Object.const_get(klass_name) + end + object = finder.find(string.gsub(/[ _]/, "").to_i) value = object.id rescue ActiveRecord::RecordNotFound invalid_format string, "The specified #{klass_name} was not found" diff --git a/spec/lib/parameter_spec.rb b/spec/lib/parameter_spec.rb index 70752ec..5acbded 100644 --- a/spec/lib/parameter_spec.rb +++ b/spec/lib/parameter_spec.rb @@ -58,5 +58,23 @@ RSpec.describe DiscourseDataExplorer::Parameter do end end end + + describe "group_id type" do + fab!(:group) + + context "when the value provided is an integer" do + it "raises an error if no such group exists" do + expect { param("group_id", :group_id, nil, false).cast_to_ruby("-999") }.to raise_error( + ::DiscourseDataExplorer::ValidationError, + ) + end + + it "returns the group id if the group exists" do + expect(param("group_id", :group_id, nil, false).cast_to_ruby(group.id.to_s)).to eq( + group.id, + ) + end + end + end end end