Rails 3 - 使用非_id列连接表

时间:2011-02-04 02:01:03

标签: ruby-on-rails-3 jointable

我正在尝试使用带有外键的连接表,该外键不以_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:   找不到关联:models_locales in model Department

我缺少什么想法?

1 个答案:

答案 0 :(得分: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