带有“references”关键字的ActiveRecord忽略“select”部分中的列

时间:2014-09-27 22:48:34

标签: sql ruby-on-rails activerecord

Option.includes(:yaoption).references(:yaoption).select('options.id, yaoptions.name').where(options: {dept_id: 100})

导致以下SQL查询:

SELECT
    options.id AS t0_r0,
    options.title AS t0_r1,
    options.dept_id AS t0_r2,
    options.mode AS t0_r3,
    options.content AS t0_r4,
    options.yaoption_id AS t0_r5,
    options.created_at AS t0_r6,
    options.updated_at AS t0_r7,
    yaoptions.id AS t1_r0,
    yaoptions.name AS t1_r1,
    options.id,
    yaoptions.name
FROM
    options
    LEFT OUTER JOIN yaoptions ON yaoptions.id = options.yaoption_id
WHERE
    options.dept_id = 100
ORDER BY
    options.id ASC

使用references关键字的ActiveRecord查询似乎忽略了select部分。

我想看到:

SELECT
    options.id,
    yaoptions.name
FROM
    options
    INNER JOIN yaoptions ON yaoptions.id = options.yaoption_id
WHERE
    options.dept_id = 100

当我使用joins时,正在发送正确的查询:

Option.joins(:yaoption).select('options.id, yaoptions.name').where(options: {dept_id: 100})

但结果仅包含来自id表格的options

#<ActiveRecord::Relation [#<Option id: 1>, #<Option id: 2>, #<Option id: 3>]>

我想要一个只有指定字段的查询。

1 个答案:

答案 0 :(得分:0)

虽然inspectOption列出了id,但name属性也可以访问。