我在文件和联系人之间有一个多对多的关系,因此他们有 has_and_belongs_to_many 关系:
class Dossier < ActiveRecord::Base
has_and_belongs_to_many :contacts
和
class Contact < ActiveRecord::Base
has_and_belongs_to_many :dossiers
在 Dossiers Controller 显示方法中,我有这个:
@dossier = current_user.company.dossiers.find(params[:id])
@dossier_contacts = @dossier.contacts
但是当我请求显示 View 时,出现错误:
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
View 如下所示:
<li><%= I18n.t :dossier_nr_contacts %></li><li><%= @dossier_contacts.count.to_s %></li>
我想我已经设置了正确的关系,表格存在,但我现在不知道为什么它会给出错误。有什么线索吗?
编辑:我所做的迁移:
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
最佳答案
您的连接表名称错误。
应该是 contacts_dossiers
(默认按字母顺序)
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.
来源:http://guides.rubyonrails.org/association_basics.html#creating-join-tables-for-has_and_belongs_to_many-associations
关于ruby-on-rails - has_and_belongs_to_many 给出 "no such table"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8586848/