1

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?

1
  • Try User.select('value').values Commented May 25, 2015 at 4:55

2 Answers 2

1

Either map the ActiveRecord::Relation to be an array of your specification, or use .pluck() to do it in one step.

class GraphController < ApplicationController
  def index
  end

  def data
    render :json =>  User.select('value').map(&:value)
    # or
    # render :json =>  User.pluck('value')
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. That's what I wanted. As an educational point for me and other users, I know queries can be done in the model as well. Does this mean that it is fine to do simple queries like this in the controller but more heavy lifting stuff should be done using ActiveRecord in the model?
Any querying or filtering probably wants to be done in the model. If your translation from ActiveRecord object to something else is a complicated one, then that too might be better encapsulated in a model method you could call. But for your example here, just plucking one field, I'd say it's fine in the controller.
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

4 Comments

why do you have to declare a new controller after render :json. Can't I just serialize the render :json line?
Although I get the error NoMethodError in GraphController#index undefined method `serialize' for #<GraphController:0x00000005ace298> and it highlights the serialize :value line.
dont you want something like the above @SebastianZeki
So the render :json => User.select('value') (where value is the name of an actual field in the database) gives me this [{"id":null,"value":1},{"id":null,"value":64},{"id":null,"value":23},{"id":null,"value":22},{"id":null,"value":4}] whereas I want this [1,64,23,22,4]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.