General Failure
General Failure

Reputation: 2597

How can I access to related object by string field name in Ruby on Rails ActiveRecord?

Usually when we need to use ActiveRecord related object, we write such code:

main_object.related_object

Where main_object is instance of MainObject class and related_object is instance of RelatedObject that connected to MainObject via related_object_id field:

class MainObject < ActiveRecord::Base
     :has_one => :related_object
end

class RelatedObject < ActiveRecord::Base
     :belongs_to => :main_object
end

Count of relations might be difference and more than one. Also my task supposes custom queries where I don't know which one relation will be used.

So, I want to get related object via its name, eg:

main_object.relations['related_object']

Is it possible in Ruby on Rails ActiveRecord?

Upvotes: 4

Views: 1760

Answers (2)

General Failure
General Failure

Reputation: 2597

ActiveRecord objects has association method returns association information for name. It return ActiveRecord::Associations::* class instance that contains target method:

association = main_object.association :related_object
association.target # returns RelatedObject instance that I wanted

Upvotes: 0

j-dexx
j-dexx

Reputation: 10406

You can use public_send

main_object.public_send(:related_object)

Upvotes: 4

Related Questions