Create `seeds` for everything!
dsomel21 opened this issue · comments
Dilraj Singh commented
Description
Note: For more information about seeds, see #17
Basically, we are at the point where we some data for EVERYTHING in our app. I went ahead and created this JSON (scroll to the bottom) that should have everything that we need.
Goal
Update the seeds.rb
to create books
, chapters
, chhands
and chhand_types
, pauris
, and tuks
from the data in the JSON.
Once we have this data, it'll be able to test out code and play around in the rails console
.
Getting Started
rails c
will be your best friend- You will have to do lots of loops, and you'll have to do
Model.create()
a LOT! - A lot of our models require us to have
sequence
; you can do something like:blob.map.with_index do | chapter_blob, chapter_index|
Some Helpful Tips
# 1. Add the JSON to some file in the `lib` directory
# 2. Import it inside of your `seeds.rb` file like this:
json_data = File.read(Rails.root.join('lib', 'seedData.json'))
# 3. Parse the JSON data into a Ruby hash
blob = JSON.parse(json_data).map { |data| data.with_indifferent_access }
##
# The `with_indifferent_access` let's you access keys with symbols or strings
# Now, you can do something access the values with [:keys], too
# For example:
# blob.each do |book_blob|
# puts book_blob[:title]
# end
##
And then your code could look something like this:
blob.each.with_index(1) do |book_blob, book_index|
@book = Book.create(:id => book_index, :sequence => book_index, :title => book_blob[:title], :en_title => book_blob[:en_title])
book_blob[:chapters].each.with_index(1) do |chapter_blob, chapter_index|
@chapter = @book.chapters.create(:number => chapter_index, :title => chapter_blob[:title])
chapter_blob[:chhands].each.with_index(1) do |chhand_blob, chhand_index|
puts "Book: #{book_index}, Chapter: #{chapter_index}, Chhand: #{chhand_index}"
puts "chhand_blob: #{chhand_blob}"
end
end
end
The JSON 👇🏾
Download this Gist.
Dilraj Singh commented
@bhinder97 This will be really useful if you can get this in.
Harsimran Bhinder commented
Absolutely, I will hit it in the morning!