2011-02-04 3 views
0

Я пытаюсь использовать таблицу соединений с внешним ключом, который не заканчивается _id и указывает на первичный ключ не id. Вот что у меня есть.Rails 3 - Join Table with not _id Columns

Моя присоединиться таблица выглядит так:

[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 не может найти ассоциацию. Когда я звоню в отделение.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 как Entity. Я думаю, в моем случае я принесу его с помощью SQL. –

+0

Обратите внимание, что вы можете установить первичный ключ в таблицу модели DepartmentLocale на все, что хотите, используя метод primary_key в модели. Надеюсь, ты все получишь так, как хочешь! Удачи –