简体   繁体   English

用rails response_to json格式包含两个(或更多)模型及其一些虚拟属性?

[英]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. 在我的一项控制器操作中,我正在向用户分配一个项目,并且我想用有关该用户的一些信息和有关该项目的一些信息来响应json请求。 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 因此,在Firebug控制台中,我可以在控制台中看到响应对象

    // 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? 我有可能在JSON响应中连同模型一起返回虚拟属性吗?

Thank You! 谢谢!

知道了!这是一个解决方案:

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

This works well for me: 这对我来说很好:

SomeController
  respond_to :json


def some_action
  @response = { :user => current_user, :assignable => @project )
  respond_with @response
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM