Rails 3 - Соединить таблицу с не _id столбцами - PullRequest
0 голосов
/ 04 февраля 2011

Я пытаюсь использовать таблицу соединений с внешним ключом, который не заканчивается на _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: Не удалось найти ассоциацию: департаменты_locales в модели Department

Есть идеи, что мне не хватает?

1 Ответ

0 голосов
/ 04 февраля 2011

Похоже, вы создали смесь между 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
...