generate activerecord schema from an existing table
- Edit config/database.rb to point to the database you want copied.
rake db:schema:dump
- Create a blank migration
- Copy the relevant
create_table
lines from the schema dump and paste it into the migration file - Manually insert the migration timestamp into schema_migrations table (this applies to existing setup only as it already has the relevant table)
Rails: Creating models from existing tables?
just a theory, not sure how this would work in real app:
create models
named as ActiveRecord
convention requires, for example for table aaa_bbb_ccc_ddd
you'll create a model AaaBbb
and map this model to your table:
class AaaBbb < ActiveRecord::Base
self.table_name = "aaa_bbb_ccc_ddd"
end
or a more human example:
class AdminUser < ActiveRecord::Base
self.table_name = "my_wonderfull_admin_users"
end
Now you'll have AaaBbb
as resource in routes meaning you'll have a url like:
.../aaa_bbb/...
and if you want to use the table name name in url I guess you could rewrite the route:
get 'aaa_bbb_ccc_ddd/:id', "aaa_bbb#show", as: "aaa_bbb"
again, just a theory that might help you out. I haven't worked with such cases yet but would've start from this.
edit
to automate model creation from database:
https://github.com/bosko/rmre
but I think this will create models by rails convention with wierd names that you'll have to use as resource in your app.
A good template that I found on SO in case you want to use a model name different from table name:
class YourIdealModelName < ActiveRecord::Base
self.table_name = 'actual_table_name'
self.primary_key = 'ID'
belongs_to :other_ideal_model,
:foreign_key => 'foreign_key_on_other_table'
has_many :some_other_ideal_models,
:foreign_key => 'foreign_key_on_this_table',
:primary_key => 'primary_key_on_other_table'
end
rails 3:how to generate models for existing database tables
A Rails model doesn't show your fields, but you can still use them. Try the following. Assuming you have a Model named ModelName and a field called "name", fire up the Rails console and type:
ModelName.find_by_name('foo')
Given a name that exists in the DB, you should see results.
Rails doesn't infer relationships though, but if your database follows Rails conventions they are easily added.
Update
I've noticed this particular lack of explicitness ("magic") is a source of confusion for newbies to Rails. You can always look in schema.rb
to see the models and all the fields in one place. Also, if you would prefer to see the schema for each model in the model file, you can use the annotate_models gem, which will put the db schema in a comment at the top of the model file.
Ruby on Rails. Why schema.rb builded on existing data through db:schema:dump is almost empty?
I've got it! Two days of my life.
File used to import PostgreSQL database has at the beginning:
CREATE SCHEMA employees;
-- and later
CREATE TABLE employees.department;
I thought that since Rails generates database by rake db:structure:load
, the file's syntax is correct.
But when I create manually table users
in new empty database and then pg_dump
that new base I don't have CREATE SCHEMA
query there.
And finally rake db:schema:dump
fills schema.rb
with tables as I want:
create_table "users", id: :serial, force: :cascade do |t|
t.text "name"
end
Because that fresh pg_dump
ed file has CREATE TABLE public.users
query. public.
I think the key is in comments in database.yml
file:
# Schema search path. The server defaults to $user,public
#schema_search_path: myapp,sharedapp,public
One picture is more valuable than a thousand words: that's the differences Table users
on the right goes to schema.rb
after rake db:schema:dump
Thanks guys for the comments. It's made sure me that I do not make a terrible mistake.
Generate Rails migrations from a schema
Sure, connect your application to your database, then run
rake db:schema:dump
This will give you a db/schema.rb ready with all of your definitions. Now that you have that db/schema.rb, simply copy the contents within the declaration into a new migration. I've done this before, and it works just great.
Adding a column to an existing table in a Rails migration
If you have already run your original migration (before editing it), then you need to generate a new migration (rails generate migration add_email_to_users email:string
will do the trick).
It will create a migration file containing line:add_column :users, email, string
Then do a rake db:migrate
and it'll run the new migration, creating the new column.
If you have not yet run the original migration you can just edit it, like you're trying to do. Your migration code is almost perfect: you just need to remove the add_column
line completely (that code is trying to add a column to a table, before the table has been created, and your table creation code has already been updated to include a t.string :email
anyway).
rake db:migrate with existing database
If your models and tables already line up to Rails's naming scheme - User
model => users
table etc, and your models inherit from ActiveRecord::Base
, then you don't need to run a migration at all (and can't anyway since migrations by definition change your database and you have read-only access).
If the table names don't match up to the model names, you can either change your model names, or set self.table_name=
in your model. For example, if you have a User
model but the table is called accounts
, you can do this:
class User < ActiveRecord::Base
self.table = 'accounts'
# other stuff here
end
Read here for more info: http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name-3D
Also, you should delete your migration files. If you want to see the schema in db/schema.rb
, you can do a schema dump by running rake db:schema:dump
. That should generate the file, assuming your settings are correct in config/database.yml
.
Related Topics
Activerecord Connection Warning. (Database Connections Will Not Be Closed Automatically)
How to Remove Non-Printable/Invisible Characters in Ruby
Testing Routes with Subdomain Constraints Using Rspec
How to Get a Selenium/Ruby Bot to Wait Before Performing an Action
What Is the Purpose of 'Kernel'
Changing Songs on Jplayer by Clicking a Link, Hosted on Amazon S3
Storing Passwords for External APIs - Best Practice
Remove Subdomain from String in Ruby
How to Split a String by Commas Except Inside Parenthesis, Using a Regular Expression
How to Model a Mutual Friendship in Rails
Select Checkbox Pass Array in Ruby on Rails
Ruby Variable Name with Double Underscores
Rails Server Cannot Start; Getaddrinfo: Nodename Nor Servname Provided, or Not Known (Socketerror)