Rails: How to make has_many :through association work with Single Table Inheritance

假如想象 提交于 2019-12-11 08:14:51

问题


So in my current project I have an Article model that can have different kinds of Transactions. It has one main Transaction, but under certain circumstances it can have multiple sub-transactions.

Until now I set it up like this:

class Article < ActiveRecord::Base
  has_one :transaction, inverse_of: :article
  has_many :partial_transactions, through: :transaction, source_type: 'MultipleFixedPriceTransaction', source: 'PartialFixedPriceTransaction', inverse_of: :articles
end

class Transaction < ActiveRecord::Base
  belongs_to :article, inverse_of: :transaction # Gets inherited to all kinds of Transaction subclasses
end

class MultipleFixedPriceTransaction < Transaction
  has_many :children, class_name: 'PartialFixedPriceTransaction', foreign_key: 'parent_id', inverse_of: :parent
end

class PartialFixedPriceTransaction < Transaction
  belongs_to :parent, class_name: 'MultipleFixedPriceTransaction', inverse_of: :children
  belongs_to :article, inverse_of: :partial_transactions # Overwriting inheritance
end

Now with this set up I sometimes get errors like

ActiveRecord::Reflection::ThroughReflection#foreign_key delegated to
source_reflection.foreign_key, but source_reflection is nil:

#<ActiveRecord::Reflection::ThroughReflection:0x00000009bcc3f8 @macro=:has_many,
@name=:partial_transactions, @options={:through=>:transaction,
:source_type=>"MultipleFixedPriceTransaction",
:source=>"PartialFixedPriceTransaction", :inverse_of=>:articles, :extend=>[]},
@active_record=Article(id: integer ...

By the way, I experimented a lot with the source and source_type parameters and the ones there are just examples. I don't really know what to do with them.

So, how can I make this work? How is the association set up correctly?

Thank you.

来源:https://stackoverflow.com/questions/18613983/rails-how-to-make-has-many-through-association-work-with-single-table-inherita

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!