本文介绍了指定传递给 JSON 对象的 Rails 对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 中有一个具有属性 A、B、C、D 和 E 的对象.当通过 JSON 对象将此对象传递回客户端时,我如何告诉 rails 控制器只包含属性 A和 JSON 对象中的 D?

I have an object in Rails that has attributes A, B, C, D, and E. When passing this object back to the client-side through a JSON object, how can I tell the rails controller to only include attributes A and D in the JSON object?

在我的用户控制器中,我的代码如下:

Within my Users controller, my code is as follows:

    @user = User.find(params[:id])

    respond_to do |format|
        format.html
        format.json { render :json => @user}
    end

此代码有效,但是,返回的 JSON 对象包含 @user 对象的所有属性.在将任何内容发送回客户端之前,如何限制 JSON 对象中包含的属性?

This code works, however, the JSON object that is returned contains all the attributes of the @user object. How can I limit the attributes that are included in the JSON object before anything is sent back to the client?

更新:lucapette 提供了一些关于幕后发生的事情的良好背景.由于有时我可能希望返回所有属性,因此我最终使用了以下代码:

UPDATE: lucapette provides some good background about what's happening behind the scenes. Since there are times when I'd probably want all attributes returned, I ended up using the following code:

    format.json { render :json => @user.to_json(:only => ["id"])}

推荐答案

render :json => @user

将在@user 对象上调用to_json.to_json 方法将使用 as_json 方法来完成它的工作.因此,您可以轻松地覆盖 as_json 以仅将您想要的内容传递给客户端.如下所示:

will call to_json on the @user object. And the to_json method will use the as_json method to do its work. So you can easily override the as_json to pass only what you want to the clients. Like in the following:

def as_json options={}
  {
    attr1: attr1,
    attr2: attr2
  }
end

这篇关于指定传递给 JSON 对象的 Rails 对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:10