'access ActiveRecord Has Many associations

I have a model which has a lot of associations. What I need to do is to check whether one of those associations is not present or all of them are set correctly.

To do so, I created an array which includes all of those needs-to-be-checked fields. And created a loop through each element, but the case is that I can not access has_many related attributes with read_attribute method. It basically returns nil whenever I try to access has many associated fields.

What I am trying to do, I can access all related objects via car.drivers but I can not access the same object with car.read_attribute(:drivers) (because some of them are attributes and some are relations)

I think it's the behavior of read_attribute, so what should I use to access any (attribute or relation) on ActiveRecord object?

Regarding to the comments, it looks like no one understand what I am trying to do. I want to access the relations of one ActiveRecord object such like;

RELATIONS.each do |relation|
   puts "#{relation} exists" if @object.relation.present?
end

What I do not know about this, is there any method that I can access the related objects with their string typed name. Similar to, @object.read_attribute(:attribute_name) In that way I can create a for loop, but for relations not for the attributes



Solution 1:[1]

To do so, I used dynamical method call. Below is an example of showing it

RELATIONS.each do |relation|
   puts "#{relation} exists" unless @object.send('relation').nil?
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Baran Yeni