【发布时间】:2016-09-30 20:23:40
【问题描述】:
我正在为Discourse 开发一个插件,这意味着我可以使用class_eval 修改类,但我无法更改数据库架构。要存储有关主题模型的额外数据,我可以使用为此目的提供的 TopicCustomField 执行连接。
我能够存储和检索我需要的所有数据,但是当一次加载多个主题时,数据库性能低效,因为我的间接数据为每个主题单独加载一次。如果为每个主题一次加载这些数据会更好,就像使用预加载或包含时一样。
例如,每个 Topic 都有一个 topic_guid 和一组 parent_guid(存储在带有破折号的单个字符串中,因为顺序很重要)。这些 parent_guids 指向其他主题的 topic_guids 以及其他组的名称。
我希望能够写出类似的东西:
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:'组',primary_key::parent_guids,foreign_key::name但是这个 :through 抱怨无法在 TopicCustomField 中找到关联“:parent_guids”,并且 primary_key 实际上不会采用关联而不是 DB 列。
我也尝试了以下方法,但 :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
【问题讨论】:
-
看起来自定义预加载的一般策略在这里:mrbrdo.wordpress.com/2013/09/25/…
标签: ruby-on-rails ruby activerecord