2011-02-04 12 views
0

私は_idで終わらず、非id主キーを指す外部キーで結合テーブルを使用しようとしています。ここに私が持っているものがあります。Rails 3 - _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: Could not find the association :departments_locales in model Department

アイデアは何ですか?

答えて

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 
+0

入力いただきありがとうございます。機能的には動作しますが、私はそれをきれいに見つけることはできません。私は、 "ID"を結合テーブルのプライマリキーとして避け、department_localesをエンティティとして使用しないでください。私は私の場合、SQLを使用してフェッチすると思います。 –

+0

DepartmentLocaleモデルテーブルのプライマリキーを、モデルのprimary_keyメソッドを使用して設定することができます。あなたが望むようにそれがすべて働くことを望みます!がんばろう –

関連する問題