Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if ActiveRecord inverse_of detection worked?

According to the documentation for ActiveRecord::Associations::ClassMethods, ActiveRecord can automatically determine if a belongs_to association of one module is the inverse of a has_one or has_many association of another model.

However, I want to make sure that this detection actually succeeds on some associations I am not sure about (for instance, I have an belongs_to which doesn't exactly match the other model's name, but has class_name set). Is there a way to check that the inverse_of detection was applied to a specific association? Ideally, I would add something to the project's test suite to ensure that the association is bi-directional as intended.

like image 769
Denis Washington Avatar asked Mar 15 '23 21:03

Denis Washington


1 Answers

Start a rails console, and run:

> Rails.application.eager_load!

> ActiveRecord::Base.descendants.each {|m| puts "=== #{m} ==="; m.reflect_on_all_associations.each {|a| puts "#{a.name} => #{a.has_inverse?}"}}

It will dump a list with all your models, their associations and if known their inverse, otherwise 'false', nil or an empty string (based on why it's unknown.)

like image 78
Pelle Avatar answered Apr 26 '23 06:04

Pelle