使用.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实例返回,而不是简单的数组/哈希

当您使用joinsincludes进行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"