gpt4 book ai didi

sql - 包含和条件未给出预期 SQL 的 ActiveRecord 查询

转载 作者:数据小太阳 更新时间:2023-10-29 08:12:50 25 4
gpt4 key购买 nike

好的,这就是我遇到的问题。我有一个模型,该模型根据直通表中的条件设置了两个关系。

has_one :link_resource, through: :resource_contexts, source: :resource, conditions: ['resource_contexts.question_id = ? ', -1]
has_many :sample_plans, through: :resource_contexts, source: :resource, conditions: ['resource_contexts.question_id = ? ', -2]

然后,在我的 Controller 中,我尝试使用

@funder_templates = FunderTemplate.find(:all, include: [:sample_plans, :link_resource], conditions: {active: true})

但是不知道为什么,sql出来是这样的

ResourceContext Load (0.2ms)  SELECT `resource_contexts`.* FROM `resource_contexts` WHERE (`resource_contexts`.funder_template_id IN (2,3,4,5,6,7,8,9,10,11,12,13,14,20,21,22,23,24,25,26,27,30,40) AND (resource_contexts.question_id = -2 ))

请注意,它只查找第一个关系的条件,而不是第二个。我不知道我正在做的事情是否对 ActiveRecord 来说太复杂而无法处理,或者我是否只是写错了。任何帮助将不胜感激。

rails 3.0.20

ruby 1.9.2

编辑:澄清一下,真正搞砸的部分是@funder_templates.sample_plans 是正确的,但@funder_templates.link_resource 也是示例计划!没有包含,关系工作正常,只是没有优化。

最佳答案

你尝试了吗? @funder_templates = FunderTemplate.where(active: true).includes([:sample_plans, :link_resource])

我觉得应该可以

关于sql - 包含和条件未给出预期 SQL 的 ActiveRecord 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15821857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com