如何在Mongoid中预加载has_and_belongs_to_many关联?
Mongoid中预加载has_and_belongs_to_many关联的解决方法
你遇到的undefined method 'b_ids'错误,是因为Mongoid的has_and_belongs_to_many(habtm)关联默认不会自动生成xxx_ids字段访问器,而includes预加载依赖该字段获取关联ID集合。以下是两种可行的解决方式:
方法一:显式声明关联ID字段
在模型中手动添加存储关联ID的数组字段,Mongoid会自动维护这些字段的内容:
class A include Mongoid::Document has_and_belongs_to_many :bs, inverse_of: :as field :b_ids, type: Array, default: [] end class B include Mongoid::Document has_and_belongs_to_many :as, inverse_of: :bs field :a_ids, type: Array, default: [] end
添加字段后,执行A.where(...).includes(:bs)即可正常预加载关联数据。
方法二:使用preload替代includes
Mongoid的preload方法专门用于预加载关联,无需依赖xxx_ids方法,通过两次查询完成预加载:
A.where(...).preload(:bs)
这种方式不需要修改模型字段,适合不想额外声明字段的场景。
注意:确保两个模型都正确引入Mongoid::Document模块,否则关联配置无法生效。
内容的提问来源于stack exchange,提问作者user1130176
相关产品推荐
相关产品推荐

