首页 > 解决方案 > rails 生成的 CSV 文件无法下载

问题描述

我正在尝试将我的数据库导出到 CSV 文件并下载它,但它没有下载。我有一个包含 2 个不同操作的表单,导出到 CSV 和导出到 JSON,当我单击它们的任何提交按钮以下载生成的文件但它不起作用时,我想要这样做。当输入城市名称并单击导出到 CSV 提交按钮时,它不会下载

该模型weather_states.rb

class WeatherState < ApplicationRecord
  validates :city, presence: true
  validates :date, presence: true

  def self.to_csv
    attributets = %w[id city country feels_like temp humidity date]
    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |weather|
        csv << attributets.map { |attr| weather.send(attr) }
      end
    end
  end
end

控制器`weather_states_controller.rb

class WeatherStatesController < ApplicationController
def export
    case params[:commit]
    when 'Export to CSV'
      export_csv(params[:city], params[:date])
    when 'Export to JSON'
      export_json(params[:city], params[:date])
    end
  end
  
  private
  def export_csv(city, date)
    @weather = if city.nil? && date.nil?
                 WeatherState.new
               elsif date.nil?
                 WeatherState.where(city: city)
               elsif city.nil?
                 WeatherState.where(date: date)
               else
                 WeatherState.where(city: city, date: date)
               end
    respond_to do |format|
      format.html
      format.csv { send_data @weather.to_csv, filename: "weather-#{Data.today}.csv" }
    end
  end

  def export_json(name, date) end

end

风景export.html.erb

<h1>Export Data</h1>
<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <%= form_with(url: export_path, method: 'get', local: true) do |f| %>
        <div class="form-group">
          <%= f.label :City, style: "font-weight: bolder; font-size: large;" %>
          <%= f.text_field :city, class: 'form-control' %>
        </div>
        <div class="form-group">
          <%= f.label :Date, style: "font-weight: bolder; font-size: large;" %>
          <%= f.datetime_local_field :date, class: 'form-control' %>
        </div>
        <div class="form-group">
          <%= f.submit "Export to CSV", class: "btn btn-primary" %> |
          <%= f.submit "Export to JSON", class: "btn btn-primary" %>
        </div>
      <% end %>
    </div>
  </div>
</div>

路线文件routes.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root 'weather_states#home'
  get 'search', to: 'weather_states#search'
  get 'export', to: 'weather_states#export'
end

标签: ruby-on-railsruby-on-rails-5export-to-csv

解决方案


替换这一行

<%= form_with(url: export_path, method: 'get', local: true) do |f| %>

和...

<%= form_with(url: export_path, method: 'get', local: true, format: :csv) do |f| %>

推荐阅读