我在數據庫中將有關議會事務的數據保存爲Affair
,該數據可能屬於Councillor
或Group
。我是Ruby和ActiveRecord的新手。在以前的RoR版本中,我會使用has_and_belongs_to_many
,並且它也起作用。has_many/belongs_to RoR中的唯一關聯
class Councillor < ActiveRecord::Base
has_many :affair_holdings, :foreign_key => :councillor_id
has_many :affairs, through: :affair_holdings
end
class Affair < ActiveRecord::Base
has_many :affair_holdings, :foreign_key => :affair_id
has_many :councillors, through: :affair_holdings
end
class Affair_Holdings < ActiveRecord::Base
belongs_to :affair
belongs_to :councillor
end
在後面的代碼,我想建立一個新的關聯:
affair.councillors << Councillor.find_by(:id => 3)
但由於某種原因不能正常工作。它給我一個錯誤信息:
/Users/me/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/inheritance.rb:125:in `compute_type': uninitialized constant Affair::AffairHolding (NameError)
from /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/reflection.rb:178:in `klass'
from /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/associations/association.rb:123:in `klass'
from /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/associations/collection_association.rb:37:in `reader'
from /Users/me/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.2/lib/active_record/associations/builder/association.rb:70:in `affair_holdings'
from crawl.rb:196:in `affair'
from crawl.rb:233:in `<main>'
我的錯是什麼?我怎麼解決這個問題? 感謝您的幫助。