【问题标题】:Export data to file CSV on Ruby Rails在 Ruby Rails 上将数据导出到 CSV 文件
【发布时间】:2020-04-10 01:33:41
【问题描述】:

我正在尝试使用活动记录和 csv 类导出数据,但我没有生成的文件可以帮助查看我的代码。

当我点击导出时,没有打开从 csv 下载的对话框,我错过了什么吗?

我的控制器

def export_csv
    @contact = Contacts.find_by_sql("select * from contacts_list limit 10")
     respond_to do |format|
       format.html
       format.csv { send_data @contact.as_csv }
     end
  end

我的模型

def self.to_csv
    attributes = %w{id name mail}

    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |contact|
        csv << attributes.map{ |attr| contact.send(attr) }
      end
    end
  end

我的观点

<%= link_to( 'Export CSV' ,{ :controller => :company, :action => :export_csv, format: "csv"}, { :class => "btn-ex" } ) %>

控制台输出

Started GET "/company/export_cs" for 127.0.0.1 at 2019-12-17 11:31:26 -0200
Processing by CompanyController#export_cs as HTML

仅此而已,没有错误,没有消息警告。

【问题讨论】:

  • 你有什么问题?
  • 当我点击导出时没有打开从 csv 下载的对话框我错过了什么吗?
  • 单击链接后,转到您的 Web 服务器控制台并复制请求和响应信息。将其添加到您的问题中,不要将其粘贴到 cmets 中。
  • @Beartech 更新后的帖子对话框未打开以保存 csv 文件..
  • @mrzasa 更新帖子见

标签: ruby-on-rails ruby csv activerecord


【解决方案1】:
<%= link_to( 'Export' ,{ :controller => :company, :action => :export_csv, format: 'csv', :company_id => @company.id}, { :class => "btn-edit" } ) %>

谢谢各位,工作顺利。

【讨论】:

    【解决方案2】:

    您需要以不同的方式生成链接的 URL - 使用 URL 助手,而不是控制器/动作参数:

    <%= link_to( 'Export CSV', companies_export_csv_path(format: "csv", { :class => "btn-ex" } ) %>
    

    另请参阅:Rails link_to :format => :xlsx not generating link to .xlsx path

    【讨论】:

      猜你喜欢
      • 2015-03-06
      • 2011-09-12
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2014-08-07
      • 2014-10-20
      • 1970-01-01
      相关资源
      最近更新 更多