Petros Kyriakou
Petros Kyriakou

Reputation: 5343

Can't access JSON data returned from backend

I make an AJAX request and I get back a response saved to a data variable.

My controller:

def retrieve
  data = params[:data]
  @question = Question.find_by(id: params[:question_id])
  @choices = @question.choices
  results = []
  for d in data
    if Choice.find_by(id: d).correct
      results << d
    end
  end

  respond_to do |format|
    format.json {
      render json: {
        choices: @choices.to_json(only: [:id,:correct]),
        results: results,
        message: "success"
        }
      }
  end
end

The response:

Object {choices: "[{"id":1,"correct":true},{"id":2,"correct":false}]", results: Array[1], message: "success"}

I'm getting value undefined where there should be a value.

data.choices[0].id -> returns undefined

Upvotes: 2

Views: 189

Answers (1)

Moustafa Sallam
Moustafa Sallam

Reputation: 1132

Use as_json instead of to_json

Your code should be

@choices.as_json(only: [:id,:correct])

instead of

@choices.to_json(only: [:id,:correct])

For further information about difference between as_json and to_json please checkout this link

Simply as_json works better with complex datatypes like activerecord objects

Upvotes: 3

Related Questions