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>]>
我想要一个只有指定字段的查询。
答案 0 :(得分:0)
虽然inspect
仅Option
列出了id
,但name
属性也可以访问。