Rails model to hash, exclude attributes

后端 未结 2 1436
难免孤独
难免孤独 2021-01-02 07:50

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

{
  \"user\": {
    \"birthday\": \"2013-03-13\",
    \"email\": \"example@example\",
    \"id\": 1         


        
相关标签:
2条回答
  • 2021-01-02 08:22

    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.

    0 讨论(0)
  • 2021-01-02 08:27

    I would recommend to use this gem: https://github.com/fabrik42/acts_as_api

    0 讨论(0)
提交回复
热议问题