Reputation: 929
I have a web interface which is using a database for its contents. The database is pretty much arbitrarily designed without following any standard.
I want to write some APIs on top of this database. My front-end is going to consume these APIs.
I am using ActiveRecord as the ORM. The problem is that I am unable to define any associations or joins on my existing tables as both of these operations expect a column named id
in the referenced table.
What's the way to go about it given that I don't want to temper my existing database schema?
Upvotes: 1
Views: 157
Reputation: 160551
In the past I tried to use ActiveRecord to work with legacy databases, and was successful, however, in doing so, I was definitely going against the flow. ActiveRecord didn't want to use fields and tables with different naming conventions, so it took a lot of work. Since then it's become a bit more civilized and is more lenient in its "not invented here" attitude. But, it's also not the only ORM in town, and I have become a big fan of Sequel for this sort of task.
You can use Sequel as a substitute for ActiveRecord. It's a great ORM, that plays well with legacy databases. You can define what your :id
fields should be, along with specifying all the real field and table names if they don't map to the expected format.
Take a look at the "Cheat sheet" for an overview of how Sequel works, and "Sequel for ActiveRecord Users" for how it can replace ActiveRecord for your use.
Use:
The Sequel-talk group is very active, and can point you in the right direction if you need help. And, the main author, Jeremy Evens, is an excellent example of a project lead -- he's always been helpful.
Upvotes: 2
Reputation: 89586
I see a few options for you:
Picking one of these depends a lot on your requirements -- how fast it should be done, if the old data has to be kept (in which case you can't really go with 1.), how messed up the current schema is etc., but I think you should try to push towards option 1.
Upvotes: 0
Reputation: 1086
Consider using Sinatra instead of Rails. If all you want is just providing an API for a "ugly" database, don't start with activerecord.
Add your routes, and define SQL statements directly in your actions. Shouldn't be more costly than tinkering with activerecord's expectations.
Upvotes: 0
Reputation: 5651
When you define associations you can use additional options like :foreign_key and :primary_key to specify details about such field names.
belongs_to :person, :primary_key => "name", :foreign_key => "person_name"
Upvotes: 3