Adt
Adt

Reputation: 495

Rails API render associated objects name instead of id in form of JSON

I'm trying to implement Rails API, and I have following two models:

  1. Event

    belongs_to :location   accepts_nested_attributes_for :location
    
  2. Location

    has_many :events
    

with

event = Event.all

I'm getting location_id with other data but I want to show location.name instead of location_id for API request to index path i.e localhost:3000/api/events.

Currently i m getting response as

[{"id":5,"name":"event420","description":"22","venue":"","contact":"","cost":"","created_at":"2015-07-01T05:49:22.738Z","updated_at":"2015-07-01T05:49:22.738Z","started_at":"2015-07-01T06:00:00.000Z","ended_at":"2015-07-01T06:30:00.000Z","owner_id":6,"city_id":null,"slug":"event420","clot_id":null,"location_id":10}]

instead of location_id: 10 i want Location.name

Please suggest me, how i can do that.

Upvotes: 1

Views: 971

Answers (1)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

def index
    @events = Event.all
    respond_to do |format|
      format.html
      format.json { render :json => @events.to_json(:include => { :location => { :only => :name } }) }
    end
end

Add this code to events_controller

Upvotes: 3

Related Questions