1

I'm new to ruby on rails. Now I trying to use an existing postgresql db to build a RoR site. When I type

rake db:schema:dump

I got a file Schema.rb

ActiveRecord::Schema.define(version: 0) do

# These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "store", force: :cascade do |t|
    t.string "name"
    t.string "tel"
    t.string "addr"
    t.string "city"
  end

end

The table has attribute of

id:int (primary key)
name:varchar
tel:varchar
addr:varchar
city:varchar

How can I use Schema.rb to build a model for inserting or deleting data?

0

2 Answers 2

0

You can wrap all this in class and this class should be extend by ActiveRecord::Migratio

1:

class RunAllMigration < ActiveRecord::Migration

 enable_extension "plpgsql"

 def up
  create_table "store", force: :cascade do |t|
    t.string "name"
    t.string "tel"
    t.string "addr"
    t.string "city"
  end
 end
end

2: Open terminal and run rails console and paste that class definition

3: AllMigration.new.up

Hope this help you !!!

Sign up to request clarification or add additional context in comments.

Comments

0

schema.rb is only used when you need to create a new database based on your models (using the rails db:create command)

if you need to modify the schema of an existing database to add modify or remove a column or table, you need to create a migration file using the rails generate migration command.

For example to add a column to your Store model:

rails generate migration AddSurnameToStore surname:string

that will create a new migration file on the folder db/migrations:

class AddSurnameToStore < ActiveRecord::Migration
  def change
    add_column :store, :surname, :string
  end
end

Finally the following command will apply your migration and update your schema.rb file:

rails db:migrate

All the information about migrations can be found there: http://guides.rubyonrails.org/active_record_migrations.html

To create the corresponding model on your application, you just need to create the corresponding file on your model folder:

cat app/models/store.rb
Store < ActiveRecord::Base   
end

And that's it! Then you can easily create new rows on your database:

Store.create name:'hello', tel: '+32 31 14', addr: 'my address'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.