簡體   English   中英

has_many / belongs_to RoR中的唯一關聯

[英]has_many / belongs_to unique associations in RoR

我將有關議會事務的數據作為Affair保存在數據庫中,該Affair可以屬於CouncillorGroup 我是Ruby和ActiveRecord的新手。 在以前的RoR版本中,我會使用has_and_belongs_to_many ,它也可以工作。

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>'

我怎么了 我怎么解決這個問題? 感謝您的幫助。

類名應該是AffairHolding而不是Affair_Holdings

是的,班級名稱應為AffairHolding,並且始終使用班級名稱的單數和首字母大寫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM