Search code examples
ruby-on-railsslimhidden-field

Passing array into hidden_field_tag converted to string


I am trying to pass an array of hashes in a hidden_field_tag in a form but what I am getting is a string. The middleware or server or something in between is changing the hashes to strings. Before being sent to the controller, the array has already changed to a string before being assigned to the field.

  = hidden_field_tag :cities, @cities
  = hidden_field_tag :longitude, params[:longitude]
  = hidden_field_tag :address, params[:address]
  = hidden_field_tag :category, params[:category]
  = hidden_field_tag :city, @city
  = hidden_field_tag :state, @state
  = hidden_field_tag :category, @category
  = hidden_field_tag :user_id, @user.id

Solution

  • I have managed to solve the issue with the help of a senior colleague of mine by:

    1. In html/slim file:
         = hidden_field_tag :cities, @cities.map {|city| city.as_json}.to_json
    
    1. Setting in controller:
         cities = params[:cities].is_a?(String) ? JSON.parse(params[:cities]) : params[:cities]
         cities.map { |city| city.with_indifferent_access }
    

    I still am looking for suggestions if this approach is correct and would very much like to know if there is a better approach.