Return array of IDs
Hi How can I return an array from a database call.
in this format: ["141", "138", "123", "128",开发者_开发问答 "137", "139"]
In Rails 4: (ht @ri4a)
User.ids # integer array
User.ids.map(&:to_s) # string array
In 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.
If you have a has_many
, then on the has_many
side you can get the IDs for associated objects like this:
def User
has_many :tasks
end
def Task
belongs_to :user
end
ids = User.find(1).task_ids
How about:
ClassName.all.collect { |obj| obj.id }
If you use Model, there are new method - pluck. Comment.pluck(:id) #[1,2,3...]
精彩评论