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:在模型部门中找不到关联: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 回答