Rails Mongoid has_many查询未用foreign_key,无法关联Customer
问题原因及解决办法
问题根源
你遇到的问题是因为Mongoid未正确识别命名空间下的关联模型,导致生成了错误的查询条件:
Legacy::User中的has_many :customers默认会尝试关联顶级命名空间的Customer类,而非你定义的Legacy::Customer;Legacy::Customer中的belongs_to :user默认会关联顶级的User类,而非Legacy::User。
这种关联匹配错误,导致Mongoid生成了以User._id作为Customer._id的错误查询,而非使用user_id作为过滤条件。
修复步骤
1. 修正关联配置,指定完整类名
修改模型代码,在关联中明确指定class_name,确保Mongoid找到正确的关联模型:
class Legacy::User include Mongoid::Document has_many :customers, class_name: 'Legacy::Customer' field :username, type: String end class Legacy::Customer include Mongoid::Document belongs_to :user, class_name: 'Legacy::User' field :user_id, type: String end
2. 验证外键类型匹配(可选)
如果你的Legacy::User使用默认的BSON::ObjectId类型_id,而Legacy::Customer的user_id是String类型,需要确保两者格式一致:
- 要么将
Legacy::User的_id改为字符串类型(在模型中添加field :_id, type: String, default: -> { BSON::ObjectId.new.to_s }); - 要么将
Legacy::Customer的user_id类型改为BSON::ObjectId(修改field :user_id, type: BSON::ObjectId)。
3. 重新测试查询
修改完成后,再次执行Legacy::User.last.customers,此时Mongoid会生成正确的查询语句,以user_id作为过滤条件查询关联的客户记录。
内容的提问来源于stack exchange,提问作者pramodtech
相关产品推荐
相关产品推荐

