【问题标题】:Rails ".pluck" on joined tables with columns of the same name returns one value and then nilRails ".pluck" 在具有相同名称的列的连接表上返回一个值,然后返回 nil
【发布时间】:2014-11-19 05:41:20
【问题描述】:
Experiment has_many :features 
Feature belongs_to :experiment

Experiment.where("experiments.id=1")
    .joins(:features)
    .pluck("features.id", "experiments.id")

我希望这会返回每个功能的 id 和实验的 id。

[
    [1, 1],
    [2, 1],
    [3, 1],
    # ....
]

这会返回实验的 id,然后返回 nil

[
    [1, nil],
    [1, nil],
    [1, nil],
    # ....
]

这在三个方面很奇怪:

  • 即使它是一个内部连接并且只返回一个 Experiment,我也能够从特征 (features.name) 中提取列
  • 在重复列名之前一切正常。
  • 首先报告最后一个拔出的列,就像第一列被覆盖一样。切换pluck的顺序切换返回值。

这似乎是一个错误,但也许我做错了什么。有什么建议吗?

SQL 输出:

SELECT features.id, experiments.id FROM "experiments" INNER JOIN "features" ON "features"."experiment_id" = "experiments"."id" WHERE (experiments.id=1)

注意。这是一个与查询有关的简化问题,如下所示:

Experiment.where("experiments.id=1")
    .joins(feature: { child2: { :child3 } })
    .pluck("feature.id, child3.id")

【问题讨论】:

  • 不确定,试试:Experiment.where(:id=>1).joins(:features).pluck("experiments.id, features.id")?
  • @Surya Rails 很难回答.. :-) 在回答之前,我们需要创建模型并插入数据.. 工作量太大 :-)
  • 相同的输出。虽然我了解到在选择要搜索的正确列时,哈希比字符串 ("id=1") 更智能。
  • 你用的是哪个版本的rails?
  • Rails 版本 4.1.1 :)

标签: sql ruby-on-rails ruby


【解决方案1】:

这有点棘手。由于有一个INNER JOIN,因此在这种情况下,查询只产生一个id。您实际上可以反过来形成查询:

Feature.joins(:experiment)
       .where(features: { experiment_id: 1 })
       .pluck(:id, :experiment_id)

或者:

Feature.joins(:experiment)
       .where(experiments: { id: 1 })
       .pluck(:id, :experiment_id)

【讨论】:

  • 老兄! features: { experiment_id: 1 } 语法在做什么?
  • where 内,该方法将查找表:features 并形成如下查询:features.experiment_id = 1 :)
  • 我从未见过这种语法(对我来说是新的)。你在哪里找到的?
  • 在此处查找“平等条件”部分:edgeguides.rubyonrails.org/active_record_querying.html
  • 感谢..提供链接。
【解决方案2】:

在发布到 rails github 后,我发现我的具体问题在最新的 rails 版本 (4.1.6) 中得到解决。

https://github.com/rails/rails/issues/17049

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2020-09-24
    • 2022-12-03
    相关资源
    最近更新 更多