【问题标题】:Rails 3 - Join Table with not _id ColumnsRails 3 - 加入非 _id 列的表
【发布时间】:2011-02-04 02:01:03
【问题描述】:

我正在尝试使用具有不以 _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

任何想法我错过了什么?

【问题讨论】:

    标签: ruby-on-rails-3 jointable


    【解决方案1】:

    您似乎在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
    

    【讨论】:

    • 感谢您的意见。从功能上讲,它可以工作,但我觉得它不干净。我想避免“id”作为连接表中的主键,而不是使用 department_locales 作为实体。我想就我而言,我会使用 SQL 来获取它。
    • 请注意,您可以使用模型中的 primary_key 方法将 DepartmentLocale 模型表的主键设置为您想要的任何值。希望你能像你想要的那样工作!祝你好运
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多