首页 > 解决方案 > 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?

我尝试了很多组合,但仍然不起作用......

标签: ruby-on-railsactiverecordhas-many-through

解决方案


您在模型中指定:source不正确。您需要从更改为:has_one :recipientInvoice:company:recipient

class Invoice < ApplicationRecord
  belongs_to :main_transaction
  has_one :recipient, :through => :main_transaction, source: :recipient
end

推荐阅读