我有一个名为“Notation”的模型,其属性为“name”和“tag” 在其 Controller 中,有一个操作将返回一个 json,其中包含包含所有“标签”值(所有模型记录中的“标签”值)的数组。
我已经实现了这个:
@tags = Notation.all.map{ |notation| notation.tag }
render json: @tags
这可行,但是我检查了控制台并看到了已查询的 SQL:
SELECT "notations".* FROM "notations"
我想知道是否有另一种方法使用 ActiveRecord 只查询“标签”属性(主要是因为性能问题),或者这是我不必担心的事情
最佳答案
当使用all
时,您将从模型中获取所有属性。
您可以使用 select
并仅询问 tag 属性,并且您将给出类似“SELECT "notations"."tag"FROM "notations"
"的查询但您会得到一个 Notation::ActiveRecord_Relation
对象类型,并且您应该使用 map 来仅获取具有所需属性的数组。
Visit.select(:name).map(&:name)
要跳过 map
部分来创建数组,您可以使用 pluck,如下所示:
@tags = Notation.pluck :tag
render json: @tags
这也应该只查询 Notation 对象中的 tag
属性:
SELECT "notations"."tag" FROM "notations"
关于ruby-on-rails - rails : build array with the value from a certain model attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47178408/