RajSharma RajSharma - 25 days ago 4
Ruby Question

Rails and Heroku: How to add records to database?

I am new rails. I've developed a new app which shows image logos and my database contain url for these images-

In my local development environment I've added records into the database manually. My migration file for creation table looks like as follows-

class CreateBooks < ActiveRecord::Migration[5.0]
def change
create_table :books do |t|
t.string :title
t.string :author
t.string :category
t.text :description
t.text :logo_url
t.string :pdf_file_url



def get_all_books
# @books = Book.find(2);
@books = Book.where(:id => 1..3)
render :json => @books

My question is there any other way to add records to my books table?

And when I deploy my app to heroku how to add these records to heroku also?


You can create a migration file to add columns to your table, for instance if you want to add the amount of pages to the book as integer you can do this:

rails generate migration AddPagesToBooks pages:integer

and then run rake db:migrate or rails db:migrate (on rails 5+)

And to add them to your Heroku application you can use heroku run rake db:migrate


If you want to add records to your database you can use your db/seeds.rb file

In there you can do something like this:

100.times do |i|
  Book.create!(title: "book ##{i}", author: "Author ##{i}.",
              category: "category ##{i}", description: "description ##{i}",          
              logo_url: "/logo/logo##{i}", pdf_file_url: "/pdf/file##{i}")

And then run rails db:seed or rake db:seed

This will create 100 records of book with ##{i} being numbers 1-100.

You can also check this video to get a better understanding.