Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
包含和条件的ActiveRecord查询未提供预期的SQL_Sql_Ruby On Rails_Ruby_Ruby On Rails 3_Rails Activerecord - Fatal编程技术网

包含和条件的ActiveRecord查询未提供预期的SQL

包含和条件的ActiveRecord查询未提供预期的SQL,sql,ruby-on-rails,ruby,ruby-on-rails-3,rails-activerecord,Sql,Ruby On Rails,Ruby,Ruby On Rails 3,Rails Activerecord,好的,这是我遇到的问题。我有一个模型,它有两个关系设置在一个直通表中的条件上 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:

好的,这是我遇到的问题。我有一个模型,它有两个关系设置在一个直通表中的条件上

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]
然后,在我的控制器中,我试图使用

@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\u templates.sample\u plans是正确的,但是@funder\u templates.link\u资源也是示例计划!如果没有include,关系就可以正常工作,只是没有得到优化。

您尝试过吗@funder\u templates=FunderTemplate.where(活动:true)。包括([:示例\u计划,:链接\u资源])


我想,它应该会起作用。

你写的
包括:[:示例计划,:链接资源]
-这两种关系都是。@Mik\u Die这不是我写的吗?如果你想尝试使用更新的语法
@funder\u templates=FunderTemplate.all.includes([:sample\u plans,:link\u resource])。其中(:active=>true)
@depa我尝试过funder\u templates=FunderTemplate.includes([:link\u resource,:sample\u plans])。其中(active:true)出现了相同的问题。funder_templates.sample_计划和funder_templates.link_资源都是示例_计划。出于某种原因,它没有得到第二个includes关系。您是否有
has\u many:resource\u context
行?你应该这样做。你可能没有看到我对depa的评论,但我尝试了
@funder\u templates=FunderTemplate.includes([:link\u resource,:sample\u plans])。其中(active:true)
。这产生了相同的结果,当我看@funder_templates.link_resource和@funder_templates.sample_计划时,它们都是样本计划。我最终选择了一条不同的路线(类似的效率),因为我相信这是活动记录中的一个bug。可能是我们在生产中使用的版本(3.0.20)。