Amr Ragab
Amr Ragab

Reputation: 447

accessing multiple values from hash ruby on rails

This code snippet

room = Room.find(roomId)

returns a single column from room table, the returned value contains multiple attributes, like id, name, description, duration.

I want when coding

render json: room

to return only duration and name. Do i have to write something like that

render json: room[:duration, :name]

Upvotes: 4

Views: 127

Answers (3)

toddmetheny
toddmetheny

Reputation: 4443

query that will only give you the attributes that you want :

room = Room.select(:id, :duration, :name).find(room_id)

Upvotes: 3

max pleaner
max pleaner

Reputation: 26758

You're slightly incorrect when you say Room.find(roomId) returns a "single column from the room table". It actually returns a single row.

Anyway, there are a few ways you can do this.

A good starting point is to use the .attributes method on a model to convert it to a Hash.

So for example say you have a user with a name, email, and id columns in the database. You can call user.attributes to get { "name" => "max", "email" => "[email protected]", "id" => 5 }.

you can select just the name and email with

user.select { |k,v| k.in?("name", "email") } and then call to_json on the result.

To avoid having to write custom to_json code for each controller response, you can overwrite .attributes in the model. Say my User table has a password column that I never want to expose in my API:

class User
  def attributes
    super.reject { |k,v| v.in?("password") }
  end
end

Then, if you need to return a list of users as JSON:

render json: { users: @users.map(&:attributes) }.to_json, status: 200

The answer by Pavan will work as well, by the way.

Another approach is to use jbuilder and create json "views" for your records.

Upvotes: 0

Pavan
Pavan

Reputation: 33542

You can use the only option of as_json to include only certain attributes.

render json: room.as_json(:only => [:duration, :name])

Upvotes: 2

Related Questions