拥有具有关联但没有主要对象的数据库表的 Rails 模型的最佳方法是什么?
例如,我有一个帐户对象。我将该帐户对象存储在称为帐户服务的外部服务中。但我想将存储在外部服务中的帐户与本地应用程序首选项相关联。
更具体地说,我们可以说关联是支付方式。帐户可以有多种付款方式。我不希望将付款方式存储在外部服务中,而是存储在消费应用程序中。因此,我将有一个名为 account_ payment_methods 的表,该表将具有映射到外部服务帐户的帐户 ID 和映射到本地 payment_method 表的付款方法 ID。
我有一个 AccountPaymentMethod 模型,我可以使用它,但如果能够执行 account. payment_methods << 就太好了PaymentMethod.first 或类似的东西。
是否有现成的已知方法或者我自己编写此功能?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Ryan Bates 不久前在此屏幕广播中对此进行了介绍。我非常确定这将适用于您的场景。确保在指定关联时设置正确的主/外键属性。
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.
在 Rails 3.2+ 中,您可能需要查看 this gem。无表模型 RailsCast 将不再工作。
In Rails 3.2+, you may want to look at this gem instead. The Table-less models RailsCast won't work anymore.
我想这取决于您希望连接数据存放在哪里。
如果信息将存在于帐户服务中:
我认为您不能在非 ActiveRecord::Base 子类类上建立关联,除非从 ActiveRecord 内部侵入它们(通过创建您自己的 HasManyAssociation 子类,读取你存储的属性。)所以你可能有点不走运。
如果您希望信息存在于普通数据库中:
我可能会有一个 AccountBridge 模型,它将帐户映射到适当的表,并将关联放在那里;还将帐户的方法代理给帐户对象。然后,我将拥有名义上
have_{one,many} :account(s)
秘密代理到 AccountBridge 的对象,并拥有该关系的实际外键。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.