Ensure Contract#metadata is reliably orderable

This gets an annoyingly verbose comment, because otherwise it could be
removed and continue passing almost all the time.
This commit is contained in:
Matthew Draper 2022-02-25 23:00:37 +10:30
parent 26caacb45f
commit 8d04150709
2 changed files with 7 additions and 1 deletions

View File

@ -2108,6 +2108,8 @@ class RelationTest < ActiveRecord::TestCase
test "joins with order by custom attribute" do
companies = Company.create!([{ name: "test1" }, { name: "test2" }])
companies.each { |company| company.contracts.create! }
# In ordering by Contract#metadata, we rely on that JSON string to
# be consistent
assert_equal companies, Company.joins(:contracts).order(:metadata, :count)
assert_equal companies.reverse, Company.joins(:contracts).order(metadata: :desc, count: :desc)
end

View File

@ -23,7 +23,11 @@ class Contract < ActiveRecord::Base
end
def update_metadata
self.metadata = { company_id: company_id, developer_id: developer_id }
# 'code' makes the JSON string consistently orderable, which is used
# by RelationsTest "joins with order by custom attribute". Without
# this it would still pass 99% of the time, but fail when two
# records' company_id lexical and numeric order differ (99, 100).
self.metadata = { code: company_id && "%08x" % company_id, company_id: company_id, developer_id: developer_id }
end
end