0

Ruby-on-rails application using Javascript/coffee to access returned data to re-display as a drop-down list on view.

App/assets/Javascripts

$('document').ready ->
  if $('#x_eval_assum').length == 1
   $('#x_eval_assum')
  # evaluation assumption is saved
      .submit (event) ->
        event.preventDefault()
        data = $("#x_eval_assum").serialize()
        user_save_name = data.user_save_name
        drill_id = $('.form.assumption').attr('data-drillid') 
        $.post "/drills/#{drill_id}/discovery_target_saved.json", data, (res)-> 
          console.log res  # response shown below

          # line causing errors - how do I access whats in res
          for assumption in res.assumptions
             # $(select).append(<option val="id" 

Using developer -> tools to view res (e.g. data) returned to coffeescript from controller

data: Array[12]
    0: Object
        id: "c-22"
        name: "Gas, ADO"
        index: 0
        ...
    1: Object
    ...

app/controllers/drills

...
  def discovery_target_saved
    @evaluation_assumption = EvaluationAssumption.new(evaluation_assumption_params)
    load_evaluation_assumption_selections
    render json: {data: @selections}
  end

...

that part of view displaying the discovery targets

...
    <td id="discovery_targets" data-targets="<%= @probability_json %>">  
             <%= select("name", "id", 
                 @selections.collect {|r| [ r["name"], r["id"] ] },
                 { :include_blank => false })  %>
    </td>

thanks - Pierre

1 Answer 1

1

Look at your controller:

render json: {data: @selections}

That means that you're returning a Hash which contains a data key whose value will be an array of something. Then look at what's in your console:

data: Array[12]
    0: Object
        id: "c-22"
        name: "Gas, ADO"
        index: 0
     ...

That means that res.data is an array of 12 items and each item has id, name, ... properties. That means that you want to:

for assumption in res.data
  ...

do access the data.

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

2 Comments

Just tried it and it worked - thanks. How do I work through each id
You should be able to look at assumption.id inside the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.