ruby-on-rails - has_many :through :: HasManyThroughOrderError
问题描述
我对 ActiveRecords 和 class_name 的 has_many 有疑问。
我有这些模型:
main_transaction.rb
class MainTransaction < ApplicationRecord
belongs_to :supplier, :class_name => 'Company'
belongs_to :recipient, :class_name => 'Company'
has_many :invoices
end
发票.rb
class Invoice < ApplicationRecord
belongs_to :main_transaction
has_one :recipient, :through => :main_transaction, source: :company
end
公司.rb
class Company
has_many :main_transactions
has_many :invoices, through: :main_transactions
end
问题是,当我在发票模型中执行此选择时:
def self.company_filter(companies)
joins(:main_transaction, :recipient).where("companies.company_name IN (?)", companies )
end
错误是:
Could not find the source association(s) :company in model MainTransaction. Try 'has_many :recipient, :through => :main_transaction, :source => <name>'. Is it one of supplier, recipient, invoices, main_transaction_elements, or main_transaction_attachments?
我尝试了很多组合,但仍然不起作用......
解决方案
您在模型中指定:source
不正确。您需要从更改为:has_one :recipient
Invoice
:company
:recipient
class Invoice < ApplicationRecord
belongs_to :main_transaction
has_one :recipient, :through => :main_transaction, source: :recipient
end
推荐阅读
- python - 如何使用 Transpose 和 pandas 将 xlsx excel 表中的数据推送到 sqlalchemy 数据库
- javascript - 防止 iframe 导航更改顶部窗口历史状态
- r - 如何绘制带有计算值的绘图箱线图?
- python - python中的列表模式查找器?
- ios - 使用 HTTP URL 打开 Instagram - 首先打开 IG,然后打开 Safari
- css - 如何在反应中更改 ag-grid 的 bg 颜色?
- c# - 如何直接从 datagridview 单元格更新 SQL 记录,而不使用文本框?
- c# - InvalidOperationException:列出但应该是 vm 值
- css - 为什么弹性按钮的孩子不能伸展到全高?
- c - 找不到英特尔 C++ 编译器 17.0(平台工具集 = '英特尔 C++ 编译器 17.0')的构建工具