如何在ruby中将新属性包含到我的json数组中?

时间:2018-05-12 19:20:09

标签: ruby-on-rails json ruby api

我有User对象,每个用户都有{a Tag(tag_id属性) 我想在json中返回User.all信息,并将所有Tag属性添加到guether。

所以我有

users = User.where(some condition)
response = { token: current_user.token, users: users }
render json: response

我得到了

"token":"token_value",
"users":[{ each user info here and also "tag_id":1}...]

我想要

"token":"token_value",
"users":[
    { each user info here and tag info inside each user "tag":{ tag info here }}...
]

我该怎么做?

我已经尝试了almost duplicade question

的所有答案

只有一个"工作",我尝试:

users = User.where(some condition).to_json(include: [:tag])
response = { token: current_user.token, users: users }
render json: response

但现在我的json看起来错了:

{"token":"9ce32ecb324dccdd7a3e691bd8eab404",
"users":"[
{\"id\":377,\"nome\":\"CAIXA-ALM-CPARK-PE-ELE-0203-PAV00-nomeDoarquivo.dwg\",\"endereco\":\"https://localhost-gus.s3.us-west-2.amazonaws.com/users/9/f8770023-00e9-401c-884b-a97d16cae10c/CAIXA-ALM-CPARK-PE-ELE-0203-PAV00-nomeDoarquivo.dwg\",\"s3_key\":\"users/9/f8770023-00e9-401c-884b-a97d16cae10c/CAIXA-ALM-CPARK-PE-ELE-0203-PAV00-nomeDoarquivo.dwg\",\"deletado\":\"NÃO\",\"tamanho\":3205827,\"user_id\":9,\"created_at\":\"2018-05-12T11:19:55.961-03:00\",\"updated_at\":\"2018-05-12T11:19:55.961-03:00\",\"tag_id\":7,\"upload_date\":\"2018-05-12T11:19:55.960-03:00\",\
"tag\":{\"id\":7,\"nome\":\"ELÉTRICA\",\"cor\":\"#4A148C\",\"created_at\":\"2018-04-05T09:06:35.227-03:00\",\"updated_at\":\"2018-04-05T09:06:35.227-03:00\",\"abreviacao\":\"ELE\"}}
]"}

我得到了每个属性,我不知道为什么

但如果我在回复时没有使用令牌,那么工作正常:

users = User.where(some condition).to_json(include: [:tag])
response = { users: users }
render json: response

我已经编辑了这个问题,因为它被标记为重复,但正如我在上面说明的那样,它并不重复。所以我按照this meta.stackexchange link的说明进行操作,因此拥有正确权限的人可以解决此问题。

1 个答案:

答案 0 :(得分:2)

使用as_json

as_json返回模型对象的哈希表示,而to_json返回JSON对象。

> { :name => "Test", 'age' => 25 }.to_json
"{\"name\":\"Test\",\"age\":25,}"

> { :name => "Test", 'age' => 25, }.as_json
{"name"=>"Test", "age"=>25,}