ruby-on-rails - 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
解决方案
替换这一行
<%= form_with(url: export_path, method: 'get', local: true) do |f| %>
和...
<%= form_with(url: export_path, method: 'get', local: true, format: :csv) do |f| %>
推荐阅读
- python - 检查距离并从列表中删除
- json - Loop through Map in groovy
- qt - 如何在可滚动列表中显示文本和图像?
- primefaces - primefaces 文本编辑器中的高级布局
- javascript - 在提交时获取选择框的值并将其附加一个 URL 并在附加后重定向到该 URL
- selenium - 量角器远程 Seleniumbox:SELF_SIGNED_CERT_IN_CHAIN 错误
- sql - 在PostgreSQL中将字符串转换为数组数组
- python-3.x - 无法导入路径中的 pip 安装模块
- jenkins - Jenkins 中的凭据绑定会导致问题
- php - Laravel Mail assertSent 和 assertQueued 在测试中不起作用