Access to multiple values ​​from a hash ruby ​​on rails

This piece of code

room = Room.find(roomId)

returns a single column of the table of rooms, the return value contains several attributes, such as id, name, description, duration.

I want when coding

render json: room

for refund only durationand name. Should I write something like this

render json: room[:duration, :name]
+4
source share
3 answers

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

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

which will give you only the attributes you want:

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

, , Room.find(roomId) " ". .

, .

.attributes .

, , , . user.attributes, { "name" => "max", "email" => "max@max.com", "id" => 5 }.

user.select { |k,v| k.in?("name", "email") }, to_json .

to_json , .attributes . , , API:

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

, JSON:

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

, .

Another approach is to use jbuilderand create json views for your posts.

0
source

All Articles