Sachin
Sachin

Reputation: 135

json rendering issue in rails

I have added following code in user.rb.

def as_json(options={})
  h = super(:only => [:id, :content, :created_at, :updated_at])
  h
end

But in another api I have to get username and address as well. But producing these four fields when rendering json. How can I get both outputs. Thanks in advance

Upvotes: 0

Views: 44

Answers (2)

Bala Karthik
Bala Karthik

Reputation: 1413

Let the two API be

this API should return username and address too

def api1
  User.first.as_json(user_info: true)
end

this does not need to return username and address

def api2
  User.first.as_json(user_info: false)
end

let the user.rb be

 class User < ApplicationRecord
   def as_json(options = {})

     if options[:user_info] == true
       user = super(:only => [:id, :content, :created_at, :updated_at, :username, :address])
     else 
       user = super(:only => [:id, :content, :created_at, :updated_at])
     end 
     user
   end 
end

Upvotes: 2

Sajan
Sajan

Reputation: 1923

I don't have any better idea but I think you can use except like:

def as_json(options={})
  h = super(:only => [:id, :content, :created_at, :updated_at, :username, :address])
  h
end

Then when rendering you can use @yourVariable.as_json(except: [:username, :address]) when you don't need those or you can use only instead of except

Upvotes: 0

Related Questions