1

In my view I save an array of hashes in a hidden field

    <div>
       <%= hidden_field_tag :data_filtered, :value => @data_filtered %>
    </div>

My javascript is

$(document).ready(function(){
    freezeTopRow($('#dataTable'));
    $("#export").click(function(){
        var data1 = $("#data_filtered").val()
        $.ajax({
            type: "POST",
            url: "export",
            dataType: 'json',
            data: {data_filtered: data1}
        });
    });
});

My controller is

  def export
    CSV.open("data.csv", "wb") do |csv|
       csv << params[:data_filtered].first.keys
       @data_filtered.each do |hash|
       csv << hash.values
      end
    end
  end

When I view params[:data_filtered] after it has been returned to the controller i see a string:

 "{:value=>[{"a"=>nil, "b"=>nil, "c"=>0}]}"

But I want it to be in its original form of (array of hashes, in this case just 1 hash) half the problem is the :value. I don't want that to be stored and I don't know how to parse that to get just the array. Basically i want

[{"a"=>nil, "b"=>nil, "c"=>0]
3
  • What is @data_filtered in your view? Is it a Hash perhaps? Commented Jul 1, 2013 at 18:33
  • @data_filtered is an array of hashes Commented Jul 1, 2013 at 18:41
  • Have you considered serializing it manually to a known format so that you can easily unpack it? You're getting the result of calling to_s and that's not meant to be easily parsed. If you use JSON then parsing becomes easier. Commented Jul 1, 2013 at 18:56

1 Answer 1

1

Try to send json data instead of string(that contains hash). If you send string via ajax then in controller you have to eval the params which has SEVERE SECURITY issue.

using eval: (PLEASE DONT USE IT)

eval('{:value=>[{"a"=>nil, "b"=>nil, "c"=>0}]}') will produce the original hash: {:value=>[{"a"=>nil, "b"=>nil, "c"=>0}]}
Sign up to request clarification or add additional context in comments.

6 Comments

how do I send json data instead of the string?
how is that different then what i am doing?
you can find the difference if you inspect the parameter. In current implementation params[:data_filtered] is just a string, but if you send data like: data: {data_filtered: {value: [...]}} then you can get the actual parameters using params[:data_filtered][:value] in your controller
the problem is still the same. now params[:data_filtered][:value] = {:value=>[{"a"=>nil, "b"=>nil, "c"=>0}]} but I want just [{"a"=>nil, "b"=>nil, "c"=>0}]
|

Your Answer

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