导出活动记录,包括 Rails 中的关系和附件

Export Active Records including relationships and attachments in Rails

总结

我正在尝试查看是否可以导出 Active Record 及其与文件或 zip 文件的所有关系。

场景

我有一个课程模型,它看起来像这样

class Course < ActiveRecord::Base

  belongs_to :user

  has_many :lessons, -> { order("position ASC") }, dependent: :destroy

end

接下来是课程

class Lesson < ActiveRecord::Base

  belongs_to :course

  has_many :slides, dependent: :destroy

  validates :course_id, presence: true

  validates :title, presence: true

end

接下来是幻灯片

class Slide < ActiveRecord::Base

  belongs_to :lesson

  has_attached_file :file
  validates_attachment_content_type :file, :content_type => ["application/vnd.ms-excel", 
                                                            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 
                                                            "application/vnd.ms-powerpoint", 
                                                            "application/vnd.openxmlformats-officedocument.presentationml.presentation", 
                                                            "application/vnd.google-apps.presentation"]

  validates :lesson_id, presence: true

  validates :position, presence: true

  validates :title, presence: true

end

我正在使用回形针处理文件 Gem。

用例

小陶艺老师比尔class想和全国的陶艺老师吉尔分享他自制的陶艺课程。她不能一直访问互联网,因此他将向她发送一个 USB 拇指驱动器,其中包含她可以导入到她的课程申请中的课程。

Bill 登录,转到他的课程主页,然后单击 "Export"。片刻之后,file/zip 出现在他的下载文件夹中,他将其保存到拇指驱动器中。收到此消息后,Jill 登录到她的离线系统并单击 "Import Course",从而创建 Bill 在她的 Rails 申请中发送的课程的镜像副本。

问题

我需要能够将记录导出到包含这些关系等的 csv 或 xml 文件,然后我可以将其导入到同一应用程序的离线安装中。

奖金

如何将附件与导出一起打包以进行简单的导入和分发?

是的,你可以这样做,但有一些注意事项:看看 Ruby Marshall and Rails Serialize

马歇尔:"The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted."

序列化:"If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object, then specify the name of that attribute using this method and it will be handled automatically."

您还可以考虑更灵活的方式,例如JSON导出和JSON导入。这些通常使您不必发送实际的数据库,也不需要特定的版本号匹配。参见 Rails ActiveModel Serializer for JSON and gems such as jbuilder and oj