Reputation: 4570
I have User object and each user have {a Tag (tag_id attribute) I want to return User.all info in json and also add all Tag attributes toguether.
So I have
users = User.where(some condition)
response = { token: current_user.token, users: users }
render json: response
and I get
"token":"token_value",
"users":[{ each user info here and also "tag_id":1}...]
I want to get
"token":"token_value",
"users":[
{ each user info here and tag info inside each user "tag":{ tag info here }}...
]
How can I do it?
I already try all answers from this almost duplicade question
Only one "worked", I try:
users = User.where(some condition).to_json(include: [:tag])
response = { token: current_user.token, users: users }
render json: response
But now my json is look's wrong:
{"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\"}}
]"}
I got \ for each attribute and I don't know why
But if I use without token at my response, works fine:
users = User.where(some condition).to_json(include: [:tag])
response = { users: users }
render json: response
I already edited this question because it was marked as duplicate but as I explaim above it's not duplicate. So I am following the instructions from this meta.stackexchange link so someone with the right privileges can fix this.
Upvotes: 0
Views: 328
Reputation: 2510
use as_json
as_json returns a hash representation of your model object, while to_json returns a JSON object.
> { :name => "Test", 'age' => 25 }.to_json
"{\"name\":\"Test\",\"age\":25,}"
> { :name => "Test", 'age' => 25, }.as_json
{"name"=>"Test", "age"=>25,}
Upvotes: 3