Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails model to hash, exclude attributes

I am trying to form a json response that looks like this:

{
  "user": {
    "birthday": "2013-03-13",
    "email": "example@example",
    "id": 1,
    "name": null,
    "username": "example"
  },
   "other_data": "foo"
}

Before, when I was just returning the user, I used

render :json => @user, :except => [:hashed_password, :created_at, :updated_at]

to keep the hashed_password, created_at, and updated_at attributes from being sent. Is there a way to do this, but also allow additional data to be sent along with the user? Right now I'm just adding the attributes I want to send to the hash one by one, but this is obviously not ideal.

like image 861
dark_knight Avatar asked Mar 13 '13 22:03

dark_knight


1 Answers

Rendering json data first automagically calls 'as_json' on your model, which returns a ruby hash. After that, 'to_json' is called on that to get a string representation of your hash.

To achieve what you wanted, you can call something like this:

render :json => {
  :user => @user.as_json(:except => [:hashed_password]),
  :some_other_data => {}
}

In this case, there is no object which responds to 'as_json', so the controller just calls 'to_json' to turn your hash to a string.

like image 117
Alex Avatar answered Nov 15 '22 20:11

Alex