Presentation is loading. Please wait.

Presentation is loading. Please wait.

Adding Data to a Database Table Carol Wolf Computer Science.

Similar presentations


Presentation on theme: "Adding Data to a Database Table Carol Wolf Computer Science."— Presentation transcript:

1 Adding Data to a Database Table Carol Wolf Computer Science

2 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.

3 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:

4 class AddData < ActiveRecord::Migration def self.up Book.create( :isbn => '4567-8901', :author => 'Chekov', :title => 'The Cherry Orchard' ) Book.create( :isbn => ‘3412-4598’, :author => ‘Hemmingway’, :title => ‘The Sun Also Rises’ ) … end def self.down Book.delete_all end

5 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)

6 # 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 => '4567-8901', :author => 'Chekov', :title => 'The Cherry Orchard'}, {:isbn => '3412-4598', :author => 'Hemmingway', :title => 'The Sun Also Rises'}, {:isbn => '1357-2468', :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.


Download ppt "Adding Data to a Database Table Carol Wolf Computer Science."

Similar presentations


Ads by Google