2

I want to export table records in CSV format. for that i want to pass array of ids to my controller's(say 'users') action (say 'export_csv').

I have created my route like this

resources :users do
  collection do
    get "/export_csv/data", action: :export_csv, as: :export_csv
  end
end

And in my link_to tag i am passing it like this

export_csv_users_path(@data) 

Which generates url like this

/users/export_csv/data?format[]=1&format[]=2&format[]=3&format[]=4&format[]=5&format[]=6&format[]=7&format[]=8&format[]=9&format[]=10&format[]=11&format[]=12&format[]=13&format[]=14&format[]=15&format[]=16&format[]=17&format[]=18&format[]=19&format[]=20&format[]=21&format[]=22&format[]=23&format[]=24&format[]=25&format[]=26&format[]=27&format[]=28&format[]=29&...

Due to which rails generates error

406 Not Acceptable 

I want to know that is there any method through which i can pass array of id through route, something like this

/users/export_csv/data?format[]=[1,2,3,4,...]

Please suggest better way.

Jeet
  • 1,350
  • 1
  • 15
  • 32

2 Answers2

2

You can not pass array as parameter in url. If you want to pass array, you can combine array values to form a string:

In view:

= link_to 'url_name', export_csv_users_path(:data => @data.join(','))

Then you can get it in controller and split to generate array

array_element = params[:data].split(',')
Aman Garg
  • 4,198
  • 2
  • 21
  • 29
  • 1
    this wont work if the number of ids in the are more then like 100 or so. http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers if you think they are going to be more than that , you should convert it to post. Long should always be a o no no. – Sahil Dhankhar Aug 02 '13 at 06:35
  • @sahildhankhar: you may be right, but still we can't send parameteres in the form of array either via get or post request. – Aman Garg Aug 02 '13 at 06:52
  • 1
    hey aman , thanks for the feedback with this request `/users/export_csv/data?format[]=1&format[]=2&format[]=3&format[]=4&format[]=5&format[]=6` while accessing it in controller params[:format] will give ["1","2","3","4","5","6"] http://guides.rubyonrails.org/action_controller_overview.html#hash-and-array-parameters what i meant was that the reason he was getting 406 error was beacuse format[] was getting repeated again and again in the url and it made size big. there is no reason for join(",") and split in controller, it just helped decrease the size nothing much – Sahil Dhankhar Aug 02 '13 at 07:12
2

the best way is to pass such params as data in the post request.

try converting it to(and your call to the method also):

resources :users do
  collection do
    post "/export_csv/data", action: :export_csv, as: :export_csv
  end
end
Sahil Dhankhar
  • 3,596
  • 2
  • 31
  • 44