0

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.