使用.select时,Rails会忽略第二个表中的列
例如:
r = Model.arel_table s = SomeOtherModel.arel_table Model.select(r[:id], s[:othercolumn].as('othercolumn')). joins(:someothermodel)
将产品sql:
`SELECT `model`.`id`, `someothermodel`.`othercolumn` AS othercolumn FROM `model` INNER JOIN `someothermodel` ON `model`.`id` = `someothermodel`.`model_id`
哪个是对的。 但是,加载模型时,属性othercolumn
被忽略,因为它不是Model
的属性。
它类似于急切加载和includes
,但我不希望所有列,只有指定的那么include
是不好的。
必须有一种从其他模型中获取列的简单方法吗? 我最好将项目作为Model
实例返回,而不是简单的数组/哈希
当您使用joins
或includes
进行select
时,将返回ActiveRecordRelation
。 此ActiveRecordRelation
仅由您用于调用select
的类的对象组成。 已连接模型中的选定列将添加到返回的对象中。 因为这些属性不是Model
的属性,所以当你检查这些对象时它们不会出现,我相信这是造成混淆的主要原因。
你可以在rails控制台中试试这个:
> result = Model.select(r[:id], s[:othercolumn].as('othercolumn')).joins(:someothermodel) => #]> # "othercolumn" is not shown in the result but doing the following will yield correct result > result.first.othercolumn => "myothercolumnvalue"