Rails模型进行哈希处理,排除属性 [英] Rails model to hash, exclude attributes
问题描述
我正在尝试形成如下所示的json响应:
I am trying to form 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 was just returning the user, I used
render :json => @user, :except => [:hashed_password, :created_at, :updated_at]
防止发送hashed_password,created_at和updated_at属性.有没有办法做到这一点,但还允许其他数据与用户一起发送?现在,我只是将要发送给哈希的属性一一添加,但这显然不理想.
to keep the hashed_password, created_at, and updated_at attributes from being sent. Is there a way to do this, but also allow additional data to be sent along with the user? Right now I'm just adding the attributes I want to send to the hash one by one, but this is obviously not ideal.
推荐答案
首先呈现json数据会自动在模型上调用'as_json',这会返回一个ruby哈希.之后,在此调用'to_json'以获得哈希的字符串表示形式.
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 => {}
}
在这种情况下,没有对象响应"as_json",因此控制器仅调用"to_json"将您的哈希值转换为字符串.
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.
这篇关于Rails模型进行哈希处理,排除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!