Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_and_belongs_to_many gives "no such table" error

I have a many-to_many relationship between dossier and contact and therefore they have has_and_belongs_to_many relationship:

class Dossier < ActiveRecord::Base
  has_and_belongs_to_many :contacts

and

class Contact < ActiveRecord::Base
  has_and_belongs_to_many :dossiers

In the Dossiers controller show method I have this:

@dossier = current_user.company.dossiers.find(params[:id])    
@dossier_contacts = @dossier.contacts

But when I request the show view, I get the error:

SQLite3::SQLException: no such table: contacts_dossiers: SELECT COUNT(*) FROM "contacts" INNER JOIN "contacts_dossiers" ON "contacts"."id" = "contacts_dossiers"."contact_id" WHERE "contacts_dossiers"."dossier_id" = 1

The view looks like this:

<li><%= I18n.t :dossier_nr_contacts %></li><li><%= @dossier_contacts.count.to_s %></li>

I think I have set the relationship correct, the table exists, but I don't now why it gives the error. Any clues?

Edit: The migration I did:

class CreateDossiersContactsJoinTable < ActiveRecord::Migration
  def up
    create_table :dossiers_contacts, :id => false do |t|
      t.integer :dossier_id
      t.integer :contact_id
    end
  end

  def self.down
    drop_table :dossiers_contacts
  end
end
like image 543
John Avatar asked Dec 02 '22 01:12

John


1 Answers

Your join table's name is wrong.

It should be contacts_dossiers (alphabetical order by default)

If you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of “customers_orders” because “c” outranks “o” in lexical ordering.

Source: http://guides.rubyonrails.org/association_basics.html#creating-join-tables-for-has_and_belongs_to_many-associations

like image 144
Damien Avatar answered Dec 04 '22 09:12

Damien