ruby-on-rails - 如何在 Rails 4.2 中添加 JSON 文件导出功能

标签 ruby-on-rails ruby json

所以我有兴趣编写一种方法,当我单击导出按钮时,数据库中的某些数据导出为 JSON 数据。

我该怎么做?

程序是这样的

get data from db -> convert to json -> write to file -> save file to computer.

谢谢

最佳答案

您可以轻松地使用 to_json 方法,send_data 和配置 header :

应用程序/ Controller /application_controller.rb

class ApplicationController < ActionController::Base
  def users_json
    data = User.all.to_json
    send_data data, :type => 'application/json; header=present', :disposition => "attachment; filename=users.json"
  end
end

关于ruby-on-rails - 如何在 Rails 4.2 中添加 JSON 文件导出功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31927229/

相关文章:

ruby-on-rails - 使用 mixpanel 为用户构建自定义分析仪表板

asp.net-mvc - AJAX错误处理

mysql - 提取Logstash中的特定键和值

html - 替换 rails scaffold 样式表内容

ruby - Mbox 中的数据转换为 JSON 或 CSV?

python - 使用 Django 翻译 json 文件

javascript - 在 Ruby On Rails 5 上渲染 link_to 上的部分内容而不刷新 View

ruby-on-rails - 在 Docker 容器上进行远程调试时,无法使用 Visual Studio 代码中断任何断点

javascript - rails : Calling to_json method in HTML

ruby - `def self.function` 名称是什么意思?