Rails 2.2.2 中不使用has_many_polymorphs实现多态has_many关联的可行性问询
没问题,完全可以自行实现这个逻辑!你遇到的核心问题是:Rails 2.2.2原生不支持基于多态关联的has_many :through(这就是抛出HasManyThroughAssociationPolymorphicError的原因),而has_many_polymorphs插件自动生成的反向关联(比如.pupils)因为User/Pupil同时出现在owners和participants列表里,导致命名冲突。下面给你两种可行的解决思路:
方法一:修改has_many_polymorphs配置,禁用自动反向关联
其实has_many_polymorphs插件支持关闭自动生成反向关联的选项,这样就能避免重复的.pupils/.users关联冲突。你只需要在配置里加上:skip_inverse_associations => true(对应Rails 2.2适配的插件版本):
OWNER_CLASSES = [:ilps, :lessons, :digilearning_modules, :resources, :pupil_groups, :pupils, :users] PARTICIPANT_CLASSES = [:pupils, :users, :contacts, :parent_carers] has_many_polymorphs :participants, :from => PARTICIPANT_CLASSES, :through => :conversation_participants, :order => "conversation_participants.created_at", :skip_inverse_associations => true # 禁用自动生成反向关联 has_many_polymorphs :owners, :from => OWNER_CLASSES, :through => :conversation_ownerships, :order => "conversation_ownerships.owner_type, conversation_ownerships.created_at", :skip_inverse_associations => true
这样修改后,插件只会生成你需要的participants和owners关联,不会在User、Pupil等模型上自动添加反向的conversations关联,也就不会有命名冲突了。你依然可以正常使用conversation.participants和conversation.owners来获取对应的记录,如果之后需要反向关联,可以手动在User/Pupil里添加。
方法二:完全手动实现(不依赖插件)
如果你不想引入插件,完全可以自己写查询方法来替代has_many :through的功能。首先保留你已有的中间模型,然后在Conversation类里手动实现获取参与者和所有者的方法:
第一步:保留中间模型和基础关联
class ConversationOwnership < ActiveRecord::Base belongs_to :conversation belongs_to :owner, :polymorphic => true end class ConversationParticipant < ActiveRecord::Base belongs_to :conversation belongs_to :participant, :polymorphic => true end class Conversation < ActiveRecord::Base has_many :conversation_ownerships has_many :conversation_participants end
第二步:添加自定义查询方法
class Conversation < ActiveRecord::Base has_many :conversation_ownerships has_many :conversation_participants # 获取所有参与者,按创建时间排序 def participants # 先从中间表拿到所有关联记录,避免N+1查询 participant_links = conversation_participants.includes(:participant) # 按多态类型分组,批量查询对应模型 grouped_links = participant_links.group_by(&:participant_type) grouped_links.flat_map do |type, links| klass = type.constantize klass.find(links.map(&:participant_id)) end.sort_by do |obj| # 按中间表的创建时间排序 participant_links.detect { |link| link.participant_id == obj.id && link.participant_type == obj.class.name }.created_at end end # 获取所有所有者,按类型+创建时间排序 def owners ownership_links = conversation_ownerships.includes(:owner) grouped_links = ownership_links.group_by(&:owner_type) grouped_links.flat_map do |type, links| klass = type.constantize klass.find(links.map(&:owner_id)) end.sort_by do |obj| # 先按类型排序,再按创建时间排序 [obj.class.name, ownership_links.detect { |link| link.owner_id == obj.id && link.owner_type == obj.class.name }.created_at] end end # 可选:添加添加参与者/所有者的便捷方法 def add_participant(participant) conversation_participants.create(:participant => participant) end def add_owner(owner) conversation_ownerships.create(:owner => owner) end end
这个方法的核心是手动处理多态关联的分组查询,避免了Rails原生的限制。如果你的数据量较大,还可以用更高效的SQL UNION查询来优化:
def participants # 拼接UNION查询,批量获取所有类型的参与者 query_parts = PARTICIPANT_CLASSES.map do |klass_sym| klass = klass_sym.to_s.camelize.constantize sanitize_sql([ "SELECT ?, #{klass.table_name}.*, conversation_participants.created_at AS sort_at FROM #{klass.table_name} JOIN conversation_participants ON conversation_participants.participant_id = #{klass.table_name}.id WHERE conversation_participants.participant_type = ? AND conversation_participants.conversation_id = ?", klass.name, klass.name, id ]) end union_sql = query_parts.join(" UNION ALL ") + " ORDER BY sort_at" results = ActiveRecord::Base.connection.select_all(union_sql) # 将查询结果实例化为对应的模型对象 results.map do |row| klass = row.delete('participant_type').constantize klass.instantiate(row.except('sort_at')) end end
这种方式用一次SQL查询就能获取所有参与者,性能更好,还能避免N+1问题。
总结
两种方法都是完全可行的:
- 方法一适合希望保留
has_many_polymorphs便捷性的场景,只需要调整配置就能解决冲突; - 方法二适合不想依赖第三方插件的场景,完全手动控制关联逻辑,灵活性更高。
你可以根据自己的需求选择其中一种,都能实现Conversation.first.participants和Conversation.first.owners的正常调用。
内容的提问来源于stack exchange,提问作者Max Williams

