I want to check the parent-child relationship of the model on Ruby.

Asked 2 years ago, Updated 2 years ago, 44 views

We analyze the parent-child relationship (dependent relationship) on the ER diagram to see if it really is on Ruby's source.
However, I don't know how to determine which model is associated with a parent-child relationship among Ruby's sources.
Is it possible to determine the parent-child relationship using the following example?
All this tells us is whether there is a relationship and a reference between the models.

Example 1:

class HogeGroup
  has_many:hoge_data,:class_name=>'HogeData',:foreign_key=>'hoge_id'

class HogeData
  belongs_to:hoge_group,:class_name=>'HogeGroup',:foreign_key=>'hoge_id'

Example 2:

class TestGroup
  # Has_many not listed

class TestData
  belongs_to:test_group,:class_name=>'TestGroup',:foreign_key=>'test_id'

I would appreciate it if you could let me know if there is a way to analyze it on Ruby's source.
Thank you in advance.

ruby-on-rails ruby

2022-09-30 14:58

1 Answers

I think you can use the reflect_on_all_associations method. You will receive an array of instances of ActiveRecord::Reflection::XXXReflection.

HogeGroup.reflect_on_all_associations(:has_many)
  # = > [<ActiveRecord::Reflection::HasManyToReflection>]

HogeData.reflect_on_all_associations(:belongs_to)
  # = > [<ActiveRecord::Reflection::BelongsToReflection>]

http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#M001861

https://stackoverflow.com/questions/2024205/rails-method-to-get-the-association-name-of-a-model


2022-09-30 14:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.