2

Here is my situation. I have model called Account. An account can have one or more contracts. The problem is that i'm dealing with a legacy application and each account's contracts are stored in a different database.

Example:

Account 1's contract are in account1_db.contracts. Account 2's contract are in account2_db.contracts.

The database name is a field stored in accounts table.

How can i make rails association work with this?

This is a legacy PHP application and i simply can't change it to store everything in one table. I need to make it work somehow.

I tried this, but it didn't worked:

has_many :contracts, :conditions => [lambda{ Contract.set_table_name(self.database + '.contracts'); return '1' }]

Any ideas?

4

1 回答 1

0

为什么不能选择数据库迁移?

你以错误的方式接近这个。您希望集成中的两个系统松散耦合。通过尝试将两者关联起来,您正在创建一系列相互依赖关系,这些依赖关系稍后会反过来背叛您。您尝试的方法会创建紧密耦合并降低内聚。


但是,要直接回答您的问题,请参见下文。再一次,我不建议实施我在下面所说的内容,但从技术上讲,这将是一个解决方案。

首先,rails 关联只能使用外键。事实上,所有的数据库关联都是这样工作的。没有外键就没有 ActiveRecord 关联方法,因为它违背了关联两个对象的含义。

所以你不会用 has_many 关联来完成它。相反,我只需在您的 Contract 模型上手动创建一个模拟 has_many 关联的函数。

class Account
    memoize :contracts

    def contracts
     # Load from other database in here
    end

    def contracts=
    # Push to other database in here
    end
end
于 2012-06-10T22:44:37.457 回答