How to override the 'as_json' or 'to_json' method in order to 'respond_to' without including specified information? How to override the 'as_json' or 'to_json' method in order to 'respond_to' without including specified information? ruby ruby

How to override the 'as_json' or 'to_json' method in order to 'respond_to' without including specified information?


If it is only in one action you can try:

format.json { render :json => @account, :except => :password }

if you need it for more than one action than the override would be better:

# Exclude password info from json output.def to_json(options={})  options[:except] ||= :password  superend 

the same is good for as_json

# Exclude password info from json output.def as_json(options={})  options[:except] ||= :password  superend


The best solution is to override as_json methods in your model as following:

def as_json options={}   super(     include: {ADD THE RELATIONS YOU WANT TO INCLUDE}).merge({YOU CAN MERGE EXTRA PARAMETER HERE})end

You could use only (which means that the only parameters that you've listed will be return) or use except (which means return all parameters except the listed ones).