开发者

Overriding or aliasing name of column in legacy database using Rails/ActiveRecord

I'm writing a Rails application against a legacy database. One of the tables in this legacy database has a column named object_id. Unfortunately object_id is also an attribute of every object in Ruby, so when ActiveRecord is trying to use these objects to formulate a query it is using the Ruby defined object_id, rather than the value that is in the database.

The legacy application is immense at well over a million lines of code, so simply changing the name of the column in the database would be an option of last resort.

Questions:

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

2. Is there any way in Ruby to make the object_id method beh开发者_StackOverflow社区ave differently, depending on who is calling it?

3. Can I simply override the behavior of the object_id method in my model (I assume this is a terrible idea, but had to ask)

Any suggestions are greatly appreciated.


I'm just kind of spitballing here, but you might 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's default #object_id implementation
  def object_id
    super
  end
end


Check out alias_attribute http://www.railstips.org/blog/archives/2008/06/20/alias-attribute/ I believe that it does what you are looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜