0

I have a database that's pre-populated with tables from another project..

How do I access these tables with a rails project and create new entries in them?

Thanks!

1
  • I tried creating a new model and then a "set_table_name" ... no luck so far.
    – Tommy
    Dec 23, 2010 at 20:37

1 Answer 1

0

If those tables are in the same database as your Rails project, then if they have id column as a primary key (or any other primary key that is integer type) you can just create model for each table and it should work. Of course you need to set_table_name and set_primary_key name.

With this, you should be able to:

MyModel.all
MyModel.build ...

and so on.

5
  • Yeah right now, I have a new model Abc and a method self.set_table_name to switch the table names. When I call Abc.set_table_name("new_table_name") and then an Abc.create() for the new entry, I still end up writing to the Abc table instead of new_table_name
    – Tommy
    Dec 23, 2010 at 20:54
  • You should add set_table_name your_name at the beginning of the model. Look here: api.rubyonrails.org/classes/ActiveRecord/…
    – klew
    Dec 23, 2010 at 20:57
  • Thanks yeah, that worked. However, I was wondering.. is it possible to dynamically change the table name though?
    – Tommy
    Dec 23, 2010 at 21:14
  • 1
    I don't think it is good idea. Why you need to do so? If you want to copy some data from old application, then just move it to new format and forget about old tables. Otherwise if you still need data in old format then it should probably be different models in your Rails application.
    – klew
    Dec 23, 2010 at 21:20
  • @Tommy, I see no advantage to trying to make a model fit many tables. The idea with an ORM is to create models for the various tables, then use those to access the tables, provide relationship mapping and do validations. You can just as easily write code to conditionally access a particular model, as you could try switching the table underneath a model. The difference is that the first way is how you're supposed to do it and what the ORM expects. The other way is unexpected and might not play well with the ORMs assumptions or expectations. Dec 24, 2010 at 4:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.