0

_id で終わらず、id 以外の主キーを指す外部キーを持つ結合テーブルを使用しようとしています。これが私が持っているものです。

私の結合テーブルは次のようになります。

[DepatmentsLocales] (
  department_id
  locale_code
  display_name
)

ここに私のモデルがあります:

class Locale < ActiveRecord::Base           
  has_many :departments, :through => :departments_locales
end 

class Department < ActiveRecord::Base
  has_many :locales, :through => :departments_locales
end

class DepartmentLocale < ActiveRecord::Base
  belongs_to :department
  belongs_to :locale, :foreign_key => :locale_code, :primary_key => :code
end

それでも、Rails は関連付けを見つけることができません。department.locales を呼び出すと、次のようになります。

ActiveRecord::HasManyThroughAssociationNotFoundError: モデル Department で関連付け :departments_locales が見つかりませんでした

私が見逃しているアイデアはありますか?

4

1 に答える 1

0

has_many :throughアソシエーションとアソシエーションの間でミックスを作成したhas_and_belongs_to_manyか、単に誤ったhas_many :throughアソシエーションを作成したようです。これはあなたが望むことをしますか?

# Database schema for locales
# code - primary key
# other data
class Locale < ActiveRecord::Base
  # I assume you already have code to handle the primary key for this model
  has_many :department_locales, :foreign_key => :locale_code
  has_many :departments, :through => :department_locales
end 

# Database schema for departments
# id - primary key
# other data
class Department < ActiveRecord::Base
  has_many :department_locales
  has_many :locales, :through => :department_locales, :primary_key => :code
end

# Database schema for department_locales
# Note this isn't a join table per se; it's a fully fledged model that happens to also do joins
# id - primary key FOR THIS MODEL (see http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association)
# department_id
# locale_code
# display_name
class DepartmentLocale < ActiveRecord::Base
  belongs_to :department
  belongs_to :locale, :foreign_key => :locale_code
end
于 2011-02-04T18:42:26.987 に答える