Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Ruby on Rails 3 and I would like to override (possibly in the model file) the as_json or to_json method in order to respond_to an HTTP request without including some information.

In my Account model I have

def as_json(options = {})
  super(
    :except => [
      :password
    ]
  )
end

In my controller I have

format.json {
  render :json => @account, :status => 200
}

When I make a request, for example, to /account/1.json I have back also the password attributes that, for security reasons, I don't want.

So, how can I prevent to include specified information?


I can do this and it works

format.json {
  render :json => @account.to_json(:except => [:password]), :status => 200
}

but it I need to refactor.

like image 422
user502052 Avatar asked Mar 04 '11 12:03

user502052


2 Answers

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
  super
end 

the same is good for as_json

# Exclude password info from json output.
def as_json(options={})
  options[:except] ||= :password
  super
end
like image 133
tommasop Avatar answered Oct 13 '22 22:10

tommasop


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).

like image 36
Alanoud Just Avatar answered Oct 13 '22 21:10

Alanoud Just