Overriding or aliasing a column name in an old database using Rails / ActiveRecord

I am writing a Rails application against an outdated database. One of the tables in this old database has a column with a name object_id. Unfortunately, object_idit is also an attribute of every object in Ruby, so when ActiveRecord tries to use these objects to formulate a query, it uses Ruby defined object_id, not the value, which is in the database.

A legacy application has over a million lines of code, so simply changing the column name in the database would be the last resort.

Questions:
1. Is there a way to make ActiveRecord / Rails use an alias or synonym for this column?

2. Is there any way in Ruby to make a method object_idbehave differently, depending on who calls it?
3. Can I just override the behavior of the object_id method in my model (I assume this is a terrible idea, but I had to ask)

Any suggestions are welcome.

+3
source share
2 answers

I just spit here, but you can try something like this:

class Legacy < ActiveRecord::Base
  #... all the other stuff

  #give yourself a way to access the DB version of object_id
  def oid
    attributes[:object_id]
  end
  def oid=(val)
    attributes[:object_id]=val
  end

  #restore ruby default #object_id implementation
  def object_id
    super
  end
end
+2
source

Source: https://habr.com/ru/post/1778357/


All Articles