Search code examples
mysqlruby-on-railsrubyruby-on-rails-3many-to-many

Rails searches the mistaken has_and_belongs_to_many table


I want to show all types which are related to a specific organisation in a select box of my document form. Types are part of the Ar engine. Organisations are part of another existing engine.

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

In my documents_controller I load types for forms about the before filter. The superior returns the organisation object:

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

Calling the page I get this error and ask me why he is looking for a table called organisations_types:

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'

Someone knows what I am doing wrong here?


Solution

  • Your table name isn’t map with lexical order what has_and_belongs_to_many expect. ( Expected order is organisations_types )

    So you have to add :join_table option in both model's association. Like this,

    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