gpt4 book ai didi

ruby-on-rails - rails : build array with the value from a certain model attribute

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:00 26 4
gpt4 key购买 nike

我有一个名为“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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com