2011-02-04 3 views
0

_id로 끝나지 않는 외래 키와 조인 테이블을 사용하려고합니다. 비 ID 기본 키를 가리 킵니다. 여기에 내가 가진 것이있다. 테이블을 조인 내Rails 3 - _id 열이 아닌 테이블 조인

그래서 다음과 같습니다

아직
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 

, 레일이 연결을 찾을 수 없습니다 : 여기

[DepatmentsLocales] (
    department_id 
    locale_code 
    display_name 
) 

내 모델입니다. 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

모델에서 primary_key 메소드를 사용하여 원하는대로 DepartmentLocale 모델 테이블의 기본 키를 설정할 수 있습니다. 당신이 원하는대로 모든 일을하기를 바랍니다! 행운을 빕니다 –