ruby-on-rails - has_and_belongs_to_many 给出 "no such table"错误

标签 ruby-on-rails ruby-on-rails-3.1

我在文件和联系人之间有一个多对多的关系,因此他们有 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/

相关文章:

mysql - activerecord 3.2.2 与多个连接的关联问题

ruby-on-rails-3.1 - Mongoid order_by bool 值

jquery - 带 Assets 管道的 Rails 3.1,link_to :confirm message showing twice?

ruby-on-rails - 简单的 Ruby on Rails 应用程序

ruby-on-rails - 如何在 Rails 3 应用程序中分析请求

ruby-on-rails - ElasticSearch根据restaurant_id及其平均时间显示数据

ruby-on-rails - 在 Capybara 中使用 Given/Let w/Feature/Scenario

ruby-on-rails - { "error": { "message": "Missing client_id parameter.", "type": "OAuthException", "code": 101 } }

ruby-on-rails - 这是 Rails 3 中的竞争条件问题吗?

javascript - rails 4 - 始终包含所有 javascript