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?
You can use public_send
main_object.public_send(:related_object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With