Rails 3 - Join Table with not _id Columns
I'm trying to use a join table with a foreign key that does not end with _id and points to an non id primary key. Here's what I have开发者_JAVA技巧.
My join table looks like so:
[DepatmentsLocales] (
department_id
locale_code
display_name
)
Here are my models:
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
Still, Rails cannot find the association. When I call department.locales I get:
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :departments_locales in model Department
Any ideas what I'm missing?
It looks like you've created a mix between a has_many :through
association and a has_and_belongs_to_many
association, or perhaps just a misconfigured has_many :through
association. Does this do what you want?
# 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
精彩评论