Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 421
General Failure Avatar asked Oct 23 '25 16:10

General Failure


1 Answers

You can use public_send

main_object.public_send(:related_object)

like image 53
j-dexx Avatar answered Oct 25 '25 09:10

j-dexx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!