Has_and_belongs_to_many gives an error "no such table"

I have many, many relationships between the dossiers and the contact, and therefore they have the 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 display method of the Dossiers controller, I have the following:

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

But when I request a show view, I get an error message:

 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 is as follows:

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

I think I have established the relationship correctly, the table exists, but now I don’t understand why it gives an error. Any clues?

Edit: 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 
+4
source share
2 answers

Invalid name for your join table.

It should be contacts_dossiers (alphabetically by default)

If you create a has_and_belongs_to_many association, you need to explicitly create a join table. If the connection table name is not explicitly specified with the :join_table parameter, Active Record creates the name using the lexical order of the class names. Thus, the union between customer and order models will give the default join table name “customers_orders” because “c” is superior to “o” in lexical order.

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

+18
source

If you use has_and_belongs_to_many , you also need an association table that contains pairs of identifiers for you. By convention, this table is called the plural of both joined tables! In your example, contacts_dossiers .

You need to create this table. Create the migration and create the table as follows:

 create_table :contacts_dossiers, :id => false do |f| f.integer :contact_id, :dossier_id end 

Then move the table and everything should work!

+1
source

Source: https://habr.com/ru/post/1387334/


All Articles