There are, for example, 100 div blocks on the site. Each div is a place in the cinema. When you click on one of the blocks, its unique id written to the $arr variable. Thus, I implement the functionality of the order and selection of several places at once for booking.

 $arr = []; $link = $(location).attr('href').slice(36); $('.btn-warning').each(function() { $place_id = $(this).attr('id'); $arr.push($place_id); }); $.ajax({ url: "/film_sessions/" + $link, type: "get", data: { data_value: JSON.stringify($arr) } }); 

Next I get this array using an AJAX request and send it to the Rails controller:

 before_action :get_booking_place_array, only: [:show] def get_booking_place_array @test_test = params[:data_value] puts "----------------------------------------------------------------------" puts @test_test puts "----------------------------------------------------------------------" end def show ... @test_test = [] end 

The output of the data is planned in a modal window:

 <div id="data2"> <% @test_test.each do %> <h1>hello</h1> <% end %> </div> 

The problem is that if in the show action you do not declare the @test_test variable and do not assign an empty array to it, then when entering the show page there will be an error:

undefined method `each 'for nil: NilClass

Otherwise, it will always be equal to the empty array. That is, if I select several places ( dіv ) and go to the terminal, I see such records there:

["place_5", "place_6", "place_32"]

I understand that the entry is displayed thanks to the puts @test_test line in the get_booking_place_array method.

However, using the web-console heme, I can verify that the @test_test variable on the page itself is equal to an empty array ( [] ).

It turns out that there is data in the terminal in the variable, but in the view it is not recognized, and I use two different variables. How to fix it?

  • { data_value: JSON.stringify($arr) } <- Why transfer parameters to JSON, inside of which there is a JSON string in which data is written to JSON? .-. - D-side
  • @ D-side This code was taken from the example, but the problem is not that anyway) - Maxim Cherevatov
  • And here we are about to find out ... :) - D-side
  • > The problem is that if in the show action you do not declare the @test_test variable and do not assign an empty array to it, then when entering the show page there will be an error : Neverya (c)! - Mal Skrylev

0