I am trying to export the data through rails to excel, but have a slight problem. When you go to the show.html.erb, it automatically displays the last 24 records from Reviews table. I have datetime selector on the same page to query to get the data from Reviews table as per datetime lookup. Excel/CSV export works fine for the last 24 records, but as soon as I conduct custom query through datetime selector and click on Export to xls, I still get last 24 records exported. I pretty well understand that respond_to code refreshes the controller after query and it considers that params are blank, which is the reason I am always getting last 24 records exported.
I want to export the data after custom query (through datetime query).
Does this make sense? Your kind assitance will be appreciated.
My controller code: review_controller.rb
if params[:date_from].blank? && params[:date_to].blank?
@data = Reviews.last(24).order(date_time: :desc)
elsif
@date_from = params[:date_from]
@date_to = params[:date_to]
@data = Reviews.where("date_time >= ? AND date_time <= ?", @date_from, @date_to).order(date_time: :desc)
end
respond_to do |format|
format.html
format.csv { send_data @data.to_csv }
format.xls { send_data @data.to_csv(col_sep: "\t") }
end
end
View: show.html.erb
<%= form_tag(review_path, :method => "get") do %>
<%= label_tag :date_from, 'From:' %>
<%= text_field_tag :date_from, @date_from, :id => 'datetimepicker1' %>
<%= label_tag :date_to, 'To:' %>
<%= text_field_tag :date_to, @date_to, :id => 'datetimepicker2' %>
<%= button_tag :Update, class: 'btn btn-info' %>
<% end %>`
Model: review.rb
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |products|
csv << products.attributes.values_at(*column_names)
end
end
end
Aucun commentaire:
Enregistrer un commentaire