开发者

What's the best way to have an Rails model with associations but no database table for the main object?

For example, I have an account object. I store that account object in an external service called the accounts service. But I would like to associate accounts stored in the external service with local application preferences开发者_如何学编程.

To be more specific, let's say the association is payment methods. Accounts can have multiple payment methods. I don't want the payment methods stored in the external service but rather the consuming application. So I will have a table called account_payment_methods which will have an account id that is mapped to the external service account and a payment method id mapped to a local payment_method table.

I have an AccountPaymentMethod model and I could just use that but it would be nice to be able to do account.payment_methods << PaymentMethod.first or something like that.

Is there a known method out of the box or will I be writing this functionality myself?


Ryan bates covered this some time ago in this screen-cast. I am quite sure this will work in your scenario. Make sure you set the correct primary/foreign key attributes while specifying the associations.


In Rails 3.2+, you may want to look at this gem instead. The Table-less models RailsCast won't work anymore.


I guess it depends on where you want the join data to live.

If the info will live in the Accounts service:

I don't think you can have associations on non-ActiveRecord::Base-subclass classes, short of hacking them in from the ActiveRecord internals (by making your own subclasses of HasManyAssociation, that read your stored attributes.) So you might be a bit out of luck there.

If you want the info to live in your normal db:

I would probably have an AccountBridge model which maps the Account to the appropriate tables, and put the associations there; also proxying the account's methods to the account object. Then I'd have the objects which would nominally have_{one,many} :account(s) secretly proxy to AccountBridge, and have the actual foreign keys of the relationship.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜