How to check if ActiveRecord inverse_of works?
According to the documentation for ActiveRecord :: Associations :: ClassMethods , ActiveRecord can automatically determine if the association of belongs_to
one module is inverse to an association has_one
or has_many
another model.
However, I want to make sure that this detection does succeed in some associations that I'm not sure about (for example, I have belongs_to
one that doesn't exactly match another model name, but has a class_name
set). Is there a way to check that a discovery has inverse_of
been applied to a specific association? Ideally, I would add something to the set of test projects to make sure the association is bi-directional as intended.
source to share
Start 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 list all your models, their associations and, if their reverse is known, otherwise "false", "no" or "empty string" (depending on why it is unknown.)
source to share