Ruby-on-rails 返回 ID 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4156616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:37:30  来源:igfitidea点击:

Return array of IDs

ruby-on-rails

提问by andkjaer

Hi How can I return an array from a database call.

嗨,我如何从数据库调用中返回一个数组。

in this format: ["141", "138", "123", "128", "137", "139"]

以这种格式: ["141", "138", "123", "128", "137", "139"]

回答by Harish Shetty

In Rails 4: (ht @ri4a)

在 Rails 4 中:(ht @ri4a

User.ids # integer array
User.ids.map(&:to_s) # string array

In Rails 3/4:

在 Rails 3/4 中:

User.pluck(:id) # integer array
User.pluck(:id).map(&:to_s) # string array

Old answer

旧答案

If you want to go directly to the DB:

如果你想直接去数据库:

> ActiveRecord::Base.connection.select_values("select id from users")
["1", "2", "5", "6", "7", "8", "3", "10", "11", "9"]

If you already have a model:

如果您已经有一个模型:

User.all(:select => :id).collect(&:id)

First approach is faster than the 2nd as it does not incur the cost of constructing model instances.

第一种方法比第二种方法快,因为它不会产生构建模型实例的成本。

回答by Zabba

If you have a has_many, then on the has_manyside you can get the IDs for associated objects like this:

如果您有一个has_many,那么在has_many侧面您可以获得关联对象的 ID,如下所示:

def User
  has_many :tasks
end

def Task
  belongs_to :user
end

ids = User.find(1).task_ids

回答by Samo

How about:

怎么样:

ClassName.all.collect { |obj| obj.id }

回答by Dzmitry

If you use Model, there are new method - pluck. Comment.pluck(:id) #[1,2,3...]

如果您使用模型,则有新方法 - pluck。Comment.pluck(:id) #[1,2,3...]