重写或使用Rails在传统数据库别名列名/ ActiveRecord的 [英] Overriding or aliasing name of column in legacy database using Rails/ActiveRecord

查看:187
本文介绍了重写或使用Rails在传统数据库别名列名/ ActiveRecord的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写对一个遗留数据库Rails应用程序。其中一个表在这个传统的数据库中有一个名为列的object_id 。不幸的是的object_id 也是在Ruby中每一个对象,的属性,所以当ActiveRecord的试图使用这些对象来制定它使用了Ruby定义的查询的object_id ,而不是在数据库中的值。

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.

遗留应用是巨大的,在超过100万行的code,因此只要更改数据库中列的名称将是不得已的选择。

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.

问题:
1.有没有什么办法让ActiveRecord的/ Rails的使用别名或同义词此列?
2.有没有办法在Ruby中,使的object_id 法的行为不同,这取决于谁喊呢?
3.我可以简单地重写OBJECT_ID方法的行为在我的模型(我想这是一个可怕的想法,但不得不问)

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 behave 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)

任何建议都大大AP preciated。

Any suggestions are greatly appreciated.

推荐答案

我只是那种spitballing这里,但你可以尝试这样的:

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

这篇关于重写或使用Rails在传统数据库别名列名/ ActiveRecord的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆