如何通过 Rails ActiveRecord 上的 Ruby 中的字符串字段名称访问相关对象?

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

通常当我们需要使用ActiveRecord相关对象时,我们会写这样的代码:

main_object.related_object

其中 main_objectMainObject class 的实例,related_object 是通过 [=20 连接到 MainObjectRelatedObject 的实例=] 字段:

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

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

关系的计数可能不同并且不止一个。此外,我的任务假设自定义查询,我不知道将使用哪个关系。

所以,我想通过它的名称来获取相关对象,例如:

main_object.relations['related_object']

在 Rails ActiveRecord 上的 Ruby 中有可能吗?

您可以使用public_send

main_object.public_send(:related_object)

ActiveRecord 对象具有 association 方法 returns 名称关联信息。 它 return ActiveRecord::Associations::* class 包含 target 方法的实例:

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