【问题标题】:Rails Migration Generated Join Table Schema But No FileRails 迁移生成连接表模式但没有文件
【发布时间】:2014-04-07 20:18:57
【问题描述】:

我在我的 Rails 应用程序中为 HABTM 关联创建了一个连接表。它在模式中创建了表,但从未在应用程序中生成模型文件。它还会起作用吗?为什么没有生成文件?

这是我的迁移:

class CreateBooksAuthorsJoinTable < ActiveRecord::Migration
  def change
    create_table :books_authors, id: false do |t|
      t.integer :book_id
      t.integer :author_id

      t.timestamps
    end
  end
end

模型

class Book < ActiveRecord::Base
    has_and_belongs_to_many :feeds
end

class Author < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-migrations rails-models


    【解决方案1】:

    您必须显式生成模型;它不会作为创建连接表的副产品发生。

    has_and_belongs_to_many 关联实际上不需要代表关联的模型类。它应该只是一个连接表,所以你设置的完全正确。

    此类关联的另一个选项是has_many through: 关联,它使用中间类或连接类。这在rails guide for associations 中有更详细的讨论。不过,您必须自己生成该连接模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-27
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 2013-03-23
      • 2011-05-21
      • 1970-01-01
      相关资源
      最近更新 更多