0
votes

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

1 Answers

1
votes

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.