Adding Data to a Database Table Carol Wolf Computer Science
Adding data to a books table Create a books table using rails generate scaffold book isbn:string author:string title:string We can add data to the table using the New Book link at the bottom of the index page. This is slow and for tables with a large number of fields very cumbersome. Instead a lot of data can be added at once using either a migration or modifying seeds.rb in the db folder.
Using a migration Create a migration using rails generate migration add_data This produces class AddData < ActiveRecord::Migration def self.up end def self.down end Add data to get the following:
class AddData < ActiveRecord::Migration def self.up Book.create( :isbn => ' ', :author => 'Chekov', :title => 'The Cherry Orchard' ) Book.create( :isbn => ‘ ’, :author => ‘Hemmingway’, :title => ‘The Sun Also Rises’ ) … end def self.down Book.delete_all end
Modifying seeds.rb seeds.rb is in the db folder. It is generated along with everything else when a new rails project is created. # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name => 'Daley', :city => cities.first) You can add data to it using the form indicated. It is run using rake db:seed. (Note: no plural)
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name => 'Daley', :city => cities.first) books = Book.create([ {:isbn => ' ', :author => 'Chekov', :title => 'The Cherry Orchard'}, {:isbn => ' ', :author => 'Hemmingway', :title => 'The Sun Also Rises'}, {:isbn => ' ', :author => 'Steinbeck', :title => 'The Grapes of Wrath'} ]) Note the curly braces around the hashes and the square brackets around all the data. This is shorter than the migration and easier to do. But they both work.