Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

activerecord - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...