Search code examples
ruby-on-railsrespond-to

rails respond_to json format to include two (or more) models and some of their virtual attributes?


in one of my controller actions, I am assigning a project to a user, and I want to respond to json requests to it with some info about the user and some info about the project. I can, at the moment, see all of their database attributes like this:

    # ruby code...
    # current_user.first_name #=> "Nik" db attr
    # current_user.full       #=> "Nik So" virtual attr
    # @project.name           #=> "buy something"

    format.json { render json: {user:current_user), assignable:@project}}

So in my firebug console, I can see the response object in my console

    // JS code
    success: function(r){window.test = r}

    //in console
    test.user.first_name //"Nik"
    test.assignable.name //"buy something"
    test.user.full       //undefined

Any chance that I can return virtual attributes alongside my models in the JSON response?

Thank You!


Solution

  • Got it!, here's a solution:

            format.json { render json: {user:current_user.as_json(methods:[:full]), assignable:@project}}