Rails:提供文件下载的最简单方法?

发布于 2024-09-01 00:54:28 字数 150 浏览 2 评论 0原文

大家好,目前几乎已经完成了一个 Rails 应用程序的编写,该应用程序允许以 CSV 格式下载数据库。这是第一次查看索引时生成的。

有没有一种简单的方法可以插入返回 CSV 文档的助手的链接?也就是说插入helpers的链接容易吗?这会让我一直遇到的很多问题变得容易多了

G'day guys, currently have almost finished writing a rails application that allows a CSV download of the database. This is generated when the index is first viewed.

Is there an easy way to insert a link to a helper that returns a CSV document? That is to say is it easy to insert links to helpers? This would make a lot of problems I've been having much easier

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别靠近我心 2024-09-08 00:54:28

如果您遵循一般约定,则可以为 csv 注册 mime 类型,并通过 #index 操作返回 csv 文件内容。所以你的链接助手将是这样的:

link_to 'export as csv', posts_path(:format => :csv)

If you sticked to the general conventions, then you registered a mime-type for csv and return the csv file content via your #index action. So your link helper would be like this:

link_to 'export as csv', posts_path(:format => :csv)
你爱我像她 2024-09-08 00:54:28

作为交换,如果您的文件是在索引第一次查看时生成的,而不是由 Rails 生成的,您可能希望避免标准渲染并调用 send_datasend_file 来代替(检查 api对于他们来说)。

# in your controller:
def index

  # your suff here

  @csv_path = find_or_generate_csv_file
  send_data @csv_path, :type=>"text/csv", :disposition=>'attachment'
end

protected
  def find_or_generate_csv_file
    #your file generation logic
  end

If, in exchange, your file is generated WHEN index is first view but NOT BY Rails, you may want to avoid standart render and call send_data or send_file instead (check the api for them).

# in your controller:
def index

  # your suff here

  @csv_path = find_or_generate_csv_file
  send_data @csv_path, :type=>"text/csv", :disposition=>'attachment'
end

protected
  def find_or_generate_csv_file
    #your file generation logic
  end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文