2

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
8
  • the json response not recognizing the value of choices as array instead it recongnize it as string. I think you should try the following use as_json instead of to_json Commented Sep 15, 2015 at 12:51
  • it worked thanks! bt why this error?? Commented Sep 15, 2015 at 12:54
  • check out this link to understand the difference Commented Sep 15, 2015 at 12:59
  • @MoustafaSallam - Sorry, did not read those comments before posting the answer. Please post an answer and I will delete mine. Commented Sep 15, 2015 at 12:59
  • @BroiSatse not a big deal, keep your answer. it doesn't matter Commented Sep 15, 2015 at 13:01

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

To add a little bit more - to_json uses as_json internally. The main difference between those two methods is that former returns a json string, while latter returns a hash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.