Rails model for hash, exclude attributes

I am trying to generate 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 just returned the user, I used

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

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

+5
source share
2 answers

Rendering json data first automatically calls "as_json" on your model, which returns a hash ruby. After that, to tojj is called to invoke the string representation of your hash.

, - :

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

, "as_json", "to_json", .

+15

All Articles