Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Creating models from existing tables?

I have tables already created from a different project. Their names are formatted like aaa_bbb_ccc_ddd (all non plural and some parts aren't a convention word). I have successfully created a schema from the database by reading this. But now I have to make the actual models. I've looked at RMRE, but they enforce the ActiveRecord convention on my tables and change their names, which I don't want to do because other apps depend on those tables.

What is the best way to automatically create models and a schema from existing tables?

like image 870
Derek Avatar asked Aug 12 '13 21:08

Derek


People also ask

What is a migration in Rails?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

How do I migrate a database in Ruby on Rails?

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.


1 Answers

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
like image 73
rmagnum2002 Avatar answered Nov 16 '22 01:11

rmagnum2002