【发布时间】:2022-01-15 22:57:53
【问题描述】:
我在使用 sidekiq 导入记录时收到错误 ActiveRecord::InverseOfAssociationNotFoundError (Could not find the inverse association for sponsorships (:sponsor_type in LegiscanModel::Sponsorship)。以下是我的模型。
sponsorship.rb
class LegiscanModel::Sponsorship < ApplicationRecord
belongs_to :bill, class_name: 'LegiscanModel::Bill', foreign_key: 'bill_id', inverse_of: :sponsorships
belongs_to :sponsor, class_name: 'LegiscanModel::Politician', foreign_key: :politician_id, inverse_of: :sponsorships
accepts_nested_attributes_for :sponsor
delegate :full_name, to: :sponsor, prefix: true, allow_nil: true
validates :politician_id, uniqueness: { scope: :bill }
belongs_to :sponsorship_type, class_name: 'LegiscanModel::SponsorType', foreign_key: :sponsor_type_id, inverse_of: :sponsorships
end
sponsor_type.rb
class LegiscanModel::SponsorType < ApplicationRecord
has_many :sponsorships, class_name: 'LegiscanModel::Sponsorship', inverse_of: :sponsor_type, dependent: :destroy
end
politician.rb
has_many :sponsorships, dependent: :destroy, inverse_of: :sponsor, class_name: 'LegiscanModel::Sponsorship'
sidekiq 作业(部分)
def handle_sponsors(sponsors, bill_id)
sponsors.each do |sponsor|
LegiscanModel::Politician.find_by(people_id: sponsor['people_id']).tap do |politician|
LegiscanModel::Sponsorship.find_or_create_by!(politician_id: politician.id, bill_id: bill_id, sponsor_order: sponsor['sponsor_order'], sponsor_type_id: sponsor['sponsor_type_id'])
end
end
end
【问题讨论】:
-
您在
LegiscanModel::SponsorType中有inverse_of: :sponsor_type,但在LegiscanModel::Sponsorship中,该关联称为:sponsorship_type。因此,您需要将inverse_of: :sponsor_type更改为inverse_of: :sponsorship_type或将belongs_to :sponsorship_type更改为belongs_to :sponsor_type
标签: ruby-on-rails ruby activerecord inverse-relationship