ActiveRecord::InverseOfAssociationNotFoundError (Could not find the inverse association for sponsorships (:sponsor_type in LegiscanModel::Sponsorship)使用 sidekiq 匯入記錄時出現錯誤。下面是我的模型。
贊助.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
贊助商型別.rb
class LegiscanModel::SponsorType < ApplicationRecord
has_many :sponsorships, class_name: 'LegiscanModel::Sponsorship', inverse_of: :sponsor_type, dependent: :destroy
end
政治家.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
uj5u.com熱心網友回復:
如果您實際上使用顯式嵌套正確設定類而不是使用范圍決議運算子,則可以顯著改進此代碼:
module LegiscanModel
class Sponsorship < ApplicationRecord
belongs_to :bill
belongs_to :sponsor,
class_name: 'Politician', # specifying the module is optional
inverse_of: :sponsorships
belongs_to :sponsorship_type
accepts_nested_attributes_for :sponsor
delegate :full_name, to: :sponsor, prefix: true, allow_nil: true
# should be the database column since its used to create a query
validates :politician_id, uniqueness: { scope: :bill_id }
end
end
module LegiscanModel
class SponsorshipType < ApplicationRecord
has_many :sponsorships, dependent: :destroy
end
end
雖然這似乎是一個微不足道的風格選擇,但實際上并非如此 - 通過使用module LegiscanModel您重新打開模塊并設定模塊嵌套,以便您可以參考同一名稱空間中的常量。
這也避免了由于令人驚訝的不斷查找而導致的自動加載錯誤和錯誤。::應該只在參考常量時使用 - 而不是在定義它們時。
當可以從關聯名稱派生時,您也不需要指定外鍵選項。雖然它沒有害處,但它的額外噪音。Rails 還可以自動推斷逆。如果你想通過關聯反射,你可以檢查它:
LegiscanModel::Sponsorship.reflect_on_assocation(:sponsorship_type)
.inverse
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/380421.html
