查询不存在的 habtm 记录
抱歉初学者的问题。 我在资产和项目之间有 habtm 关系。假设我正在循环遍历所有资产,我想找到与该资产无关的所有项目,但这不起作用:
Project.includes(:assets).where("assets.id != ?", asset.id)
正确的查询是什么?
sorry for the beginner's question.
I have habtm relationship between Assets and Projects. Assuming I'm looping thru all Assets I want to find all Projects not associated with this Asset, but this doesn't work:
Project.includes(:assets).where("assets.id != ?", asset.id)
what is the proper query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想查找与特定资产不关联的所有项目,类似这样的操作应该可行(未经测试,因此请根据需要进行调整):
asset_id
是资产实例的id
。另外,您不应该循环遍历资产来查找与迭代当前资产关联的所有项目,这意味着太多的数据库调用(这是所谓的 N+1 问题 - 可以找到一个很好的解释,例如 此处)。要仅通过一个查询查找与任何资产不关联的所有项目,请执行以下操作:
If you want to find all Projects not associated with a particular Asset, something like this should work (it's untested so adjust as needed):
asset_id
is theid
of your Asset instance.Also, you should not loop through the Assets to find all Projects associated with the iteration's current asset, that would mean too many database calls (it's the so called N+1 problem - a good explanation can be found eg here). To find all Projects not associated with any Asset with just one query, do this: