i’d like to know if there is any way to do autocomplete in rails 3 from a csv file. i’m trying to do this with controller render the HTML partial (i’m not sure about that).Posting the code below. i’m new to rails , your help is much appreciated
class CsvreaderController < ApplicationController
def search_csv
unless params[:search_no].nil?
@winner_attrs = nil
@search_no = params[:search_no]
@file_path = params[:file_path]
File.open(@file_path, "r") do |infile|
p "file opened in read mode"
while (line = infile.gets)
attrs = line.split("\t")
if attrs[0].to_i.equal? @search_no.to_i
p "match found"
p @winner_attrs = attrs
respond_with do |format|
format.html do
if request.xhr?
render :partial => "search_csv",
:locals => { :result => @winner_attrs },
:layout => false,
:status => :created
else
redirect_to "search_csv"
end
end
end
end
end
end
end
end
end
View file:
<script>
$('#csv_form').bind('ajax:success', function(evt, data, status, xhr) {
$('#result').html(xhr.responseText);
});
</script>
<%= form_tag( { :action => 'search_csv' },
:remote => 'true',
:id => 'csv_form'
) do
%>
<%= text_field_tag 'search_no', nil, :class => 'textbox' %>
<%= hidden_field_tag 'file_path', 'public/data/final_draw_till_10_Dec.csv' %>
<%= submit_tag "Submit", :name => 'button', :class =>'button' %>
<% end %>
<div id="result"></div>
The biggest red flag here is that you’re opening and parsing the CSV file on every request. That’s an expensive operation and certainly not worth it. Autocomplete is essentially a search operation, and CSV files are not designed for searching. You should parse the CSV file only when it is created or changed, then store its data in a structure (e.g. a database with good indices) designed for searching,