timpone
timpone

Reputation: 19969

rails as_json only: rendering not working

I have the following and am not sure why it doesn't work. It outputs the whole location object.

def test
  @l=Location.find(12)
  render :json => @l.as_json(only: [:id, :name])
end

How do I limit to only id and name? I don't want to use respond_to or respond_with block.

thx

Upvotes: 1

Views: 1573

Answers (2)

Richie Min
Richie Min

Reputation: 654

you can use ActiveRecord::Base's to_json method like this

render :json => @l.to_json(:only => [:id, :name])

Upvotes: 0

Max
Max

Reputation: 15985

Does this work?

render json: { location: { id: @l.id, name: @l.name } }

I want to edit my answer. I think this is the correct way to do it.

render json: @l.to_json(only: [:id, :name])

Upvotes: 3

Related Questions