我正在为Discourse的插件工作,这意味着我可以使用class_eval修改类,但是我无法更改数据库模式。要存储有关Topic模型的额外数据,我可以使用为此提供的TopicCustomField执行连接。预加载复杂链接/间接ActiveRecord函数/'协会'
我能够存储和检索我需要的所有数据,但是当一次加载多个主题时,数据库性能是低效的,因为我的间接数据本身是为每个主题加载一次。如果将这些数据一次性加载到每个主题中,就好像使用预加载或包含时可能会发生的情况一样。
例如,每个Topic都有一个topic_guid和一组parent_guid(由于顺序很重要,因此存储在一个带有破折号的字符串中)。这些parent_guid指向其他Topic的topic_guid以及其他Groups的名称。
我希望能写这样的:
has_many :topic_custom_fields has_many :parent_guids, -> { where(name: 'parent_guids').pluck(:value).first }, :through => :topic_custom_fields has_many :parent_groups, class_name: 'Group', primary_key: :parent_guids, foreign_key: :name
但这:通过抱怨不能够找到一个关联“:parent_guids”在TopicCustomField和primary_key不会采取实际的关联,而不是一个数据库列。
我也尝试了以下方法,但是:through子句不能使用函数作为关联。
has_many :topic_custom_fields do
def parent_guids
parent_guids_str = where(name: PARENT_GUIDS_FIELD_NAME).pluck(:value).first
return [] unless parent_guids_str
parent_guids_str.split('-').delete_if { |s| s.length == 0 }
end
def parent_groups
Group.where(name: parent_guids)
end
end
has_many :parent_guids, :through => :topic_custom_fields
has_many :parent_groups, :through => :topic_custom_fields
使用Rails 4.2.7.1
看起来像一般战略自定义预加载是在这里:https://mrbrdo.wordpress.com/2013/09/25/manually-preloading-associations-in-rails-using-custom-scopessql/ – Akh