0

I have a new project going on with an existing website and a mysql backend. Now, the website as it is right now is written in php (no framework, ouch) and the mysql tables do not follow any conventions. For example, table names are not always plural, the unique identifier per table is not always called id but something like c_id, sometimes there are no timestamp fields for created_at and updated_at, and if there are, they have a different name.

Now I want to build an admin panel for the website in Rails that will access the same database. I have two options:

  1. Change the database to follow the rails conventions and modify the php app and all queries accordingly
  2. Somehow tell Rails that it shall treat something like `c_id` as `id`, and singular names as plural names, etc.

Of course, the first option is technically feasible but probably a huge pain. This is why I would definitely prefer the second option and wonder if it is possible for each model to tell Rails how to treat things instead if they don't follow the convention. In my mind this would look something like:

class ModelClass < ActiveRecord::Base
  treat :user, as: :users
  treat :user.u_id, as: :id
  treat :user.created, as: :created_at if exists
  treat :user.last_update, as: :updated_at if exists
end

This is just pseudo-code, but you get the idea. Is something like this possible?

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
  • possible duplicate of [setting primary key for a database not named ":id"](http://stackoverflow.com/questions/9986658/setting-primary-key-for-a-database-not-named-id) – user229044 Dec 16 '12 at 15:19

1 Answers1

2

There is nothing like what you're suggesting, but you're free to call your models/columns/associations whatever you want.

class User
  set_table_name 'user' # instead of default "users"
  set_primary_key :c_id # instead of default "id"
end
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Looks good - will Rails know to set the id automatically? And how would I go about timestamp fields and find out whether they exist or not? – Dennis Hackethal Dec 16 '12 at 15:19
  • 1
    You wouldn't. You can do that, those are baked in. At best you could setup your own `after_save` callback to update the timestamps. – user229044 Dec 16 '12 at 15:20
  • Sure, it is just sometimes they exist under a different name, sometimes they don't exist at all. I guess I will have to create migrations for that. Will Rails know to set the id automatically when called c_id? And what would the command be for setting created at and updated at? Just set_created_at? – Dennis Hackethal Dec 16 '12 at 15:25
  • No, as I said, you *can't do that*. You have to setup an `after_save` callback to update your own timestamps manually. You cannot change their names, they are hardcoded as `created_at/on` and `updated_at/on` – user229044 Dec 16 '12 at 16:54