Summary
I'm trying to see if it is possible to export a Active Record and all it's relationships to a file or zip file.
Scenario
I have a Course Model it looks like this
class Course < ActiveRecord::Base
belongs_to :user
has_many :lessons, -> { order("position ASC") }, dependent: :destroy
end
Next up is Lessons
class Lesson < ActiveRecord::Base
belongs_to :course
has_many :slides, dependent: :destroy
validates :course_id, presence: true
validates :title, presence: true
end
Next up is Slides
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
I'm handling files with the Paperclip Gem.
Use Case
Bill, a teacher for a small pottery class wants to share his homemade pottery course with Jill, a pottery teacher across the country. She doesn't have internet access all the time so he's going to send her a USB thumb drive with the would course that she can import into her course application.
Bill logs in, goes to his course homepage, and clicks "Export". After a few moments a file/zip is in his downloads folder and he saves it to a thumb drive. Upon receiving this, Jill logs into her offline system and clicks "Import Course", thus create a mirror copy of the course Bill sent on her Rails application.
Problem
I need to be able to export a record to a csv or xml file that includes these relationships and whatnot, that I can then import into an offline installation of the same application.
Bonus
How would I package the attachments along with the export for simple import and distribution?
Yes, you can do this, with some caveats: look at Ruby Marshall and Rails Serialize
Marshall: "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."
Serialize: "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."
You can also consider more flexible ways, such as a JSON export and JSON import. These typically free you from having to send an actual database, and also from requiring specific version number matches. See Rails ActiveModel Serializer for JSON and gems such as jbuilder and oj.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With