【问题标题】:How to use has_many through with namespace models in Rails?如何在 Rails 中通过命名空间模型使用 has_many?
【发布时间】:2012-12-15 19:41:50
【问题描述】:

我有一个名为Accounting::Invoice的名称间隔模型

我还有一个模型叫Contact

Accounting::Invoice 通过另一个名为 Contactable 的模型有许多联系人 - 这是在发票被拆分到多个联系人的情况下。

但由于某种原因,我无法让 has_many through 关联工作。

我可以让它在一个方向上工作,例如:Contact.first.accounting_invoices,但在另一个方向上,例如:Accounting::Invoices.first.contacts 给我一个看起来像这样的错误:

SQLite3::SQLException: no such column: contactables.invoice_id...

有什么想法吗?我不确定 ActiveRecord 在哪里得到contactabes.invoice_id。我已经明确定义了我的表名和类名,以分别使用accounting_invoices 表和Accounting::Invoice 类。

【问题讨论】:

  • 请说明您如何在两个模型中设置关联,以及任何其他可能相关的模型设置(如自定义table_name)。

标签: ruby-on-rails activerecord namespaces associations


【解决方案1】:

您可以使用:foreign_key => 'accounting_invoice_id 选项告诉rails 使用哪个字段。查看has_many 的文档以获取更多信息 (http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many)。

相关部分是:

:foreign_key
Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and “_id” suffixed. So a Person class that makes a has_many association will use “person_id” as the default :foreign_key.

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2012-09-10
    • 2012-04-18
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多