Connect rails to existing postgres DB - models not seen by console and controllers

若如初见. 提交于 2019-12-13 03:23:24

问题


I have a database with several tables, each one containing columns that may not follow the rails naming convention.
Is there a tool existing to create the ActiveRecord models from those tables or do I need to do this at hand, one by one ?

If I create the ActiveRecord model for one table by hand, would this be ok though ? (no hidden DB identifier needed on top of it ?)

UPDATE

I have tried magicmodels but cannot have it working (it has been a while since it was last modified) and does not seem to be compatible with rails 3.2

What I tried then:

- change the database.yml so it points towards my existing Postresql database
- manually create my models such as:

    # app/models/user.rb
    class User < ActiveRecord::Base
    end

- run the console and tried
    User.all

=> I end up with an error saying that contant User was not initialized.  
Doesn't the console import the model automatically ? Or is that linked to the fact the configuration I did is not correct ?

回答1:


ActiveRecord works OK with legacy databases. I did a back-end system that didn't use Rails with ActiveRecord as my ORM. "ActiveRecord Without Rails" got me started. "Using ActiveRecord outside Rails" is also useful. Search Google for "use activerecord without rails" and you'll find even more.

You don't need a fully fleshed out model. Just use a base class for the tables you want and ActiveRecord will query the database for what it needs. It won't know about table relationships, but for general queries it'll do fine. Build the relationships as you go and need them.




回答2:


http://magicmodels.rubyforge.org/magic_model_generator/ may be what you're looking for. I haven't heard of many tools that give this functionality, though, as many rails apps are designed from scratch instead of given a legacy db and then creating the models from that.

You can easily create models by hand and map them to pretty much any db table. Models have a "set_table_name 'name'" that lets you over-write the rails default convention of a single model mapping to a plural db table name.



来源:https://stackoverflow.com/questions/9297972/connect-rails-to-existing-postgres-db-models-not-seen-by-console-and-controlle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!