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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With