Reverse lookup a fixture name by its id and table name

Posted . Visible to the public.

To reverse lookup a fixture by its table name and id, use the following approach on ActiveRecord::FixtureSet:

table = 'users'       # Specify the fixture table name
id = 123122           # Specify the ID to look for

# Find the fixture that matches the given ID
ActiveRecord::FixtureSet.all_loaded_fixtures[table].fixtures.find { |key, value| value['id'] == id }

Result Example:

[
  "one", # Fixture name
  #<ActiveRecord::Fixture:0x00007e79990234c8>, # ActiveRecord::Fixture object
  @fixture= { ... }, # The raw fixture hash
  @model_class= User(id: integer, ...)> # Associated model class
]

Key Details:

  • Replace 'users' with the specific table/fixture name you are targeting.
  • Replace 123122 with the desired ID for the lookup.
  • The output includes the fixture key (e.g., "one") and its related metadata.

Use this to debug or identify fixture names dynamically when working with test data.

Felix Eschey
Last edit
Felix Eschey
Keywords
rails, ruby
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2024-12-17 11:19)