how to get array from database in rails

时间:2015-05-24 21:03:05

标签: ruby-on-rails json

I would like to create an array in my controller from the underlying database, which I will eventually render in JSON.

The database is called User with the fields name:string and value:integer

At the moment I have the following in my controller:

class GraphController < ApplicationController
  def index
  end

   def data
    render :json =>  User.select('value')
  end
end

but this returns a hash of id and value whereas I would like an array of value numbers only. How can I achieve this?

2 个答案:

答案 0 :(得分:1)

将ActiveRecord :: Relation映射为规范的数组,或使用.pluck()一步完成。

class GraphController < ApplicationController
  def index
  end

  def data
    render :json =>  User.select('value').map(&:value)
    # or
    # render :json =>  User.pluck('value')
  end
end

答案 1 :(得分:0)

You can store Arrays and Hashes using ActiveRecord's serialize declaration:

class GraphController < ApplicationController
  def index
  serialize :value
  end

   def data
    render :json =>  User.value['value1', 'value2'] //etc
  end
end