Rails 搜索错误 has_and_belongs_to_many table

Rails searches the mistaken has_and_belongs_to_many table

我想在文档表单的 select 框中显示与特定组织相关的所有类型。类型是 Ar 引擎的一部分。组织是另一个现有引擎的一部分。

module Ar
  module OrganisationPatch
    extend ActiveSupport::Concern
    included do
      attr_accessible :ar_document_id

      has_many :ar_documents, :class_name => 'Ar::Document'
      has_and_belongs_to_many :ar_types, :class_name => 'Ar::Type'
    end
  end
end

module Ar
  class Type < ActiveRecord::Base
    attr_accessible :name

    has_many :documents
    has_and_belongs_to_many :organisations
  end
end

class CreateTypeOrganisations < ActiveRecord::Migration
  def change
    create_table :ar_type_organisations, id: false do |t|
      t.uuid :type_id, index: true
      t.uuid :organisation_id, index: true
    end
  end
end

在我的 documents_controller 中,我加载了有关前置过滤器的表单类型。上级returns组织对象:

def load_form_objects
  unless current_user.admin?
    @types = current_user.superior.ar_types
  else
    @types = Type.all
  end
end

调用页面时出现此错误并问我为什么他要寻找一个名为 organisations_types:

的 table

ActiveRecord::StatementInvalid in Ar/documents#new

Mysql2::Error: Table 'portal.organisations_types' doesn't exist: SELECT ar_types.* FROM ar_types INNER JOIN organisations_types ON ar_types.id = organisations_types.type_id WHERE organisations_types.organisation_id = x'891c3986b33845d08d3951645a4f27d5'

有人知道我在这里做错了什么吗?

您的 table 名字不符合 has_and_belongs_to_many 期望的词汇顺序。 (预期顺序为 organisations_types

所以你必须在两个模型的关联中添加 :join_table 选项。像这样,

has_and_belongs_to_many :ar_types, :class_name => 'Ar::Type', join_table: "ar_type_organisations"

has_and_belongs_to_many :organisations, join_table: "ar_type_organisations"

Reference