Question

I created a join table for a HABTM association in my Rails app. It created the table in the schema, but it never generated a model file in the app. Will it still work? Why did it not generate a file?

Here is my migration:

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

Models

class Book < ActiveRecord::Base
    has_and_belongs_to_many :feeds
end

class Author < ActiveRecord::Base
  has_and_belongs_to_many :posts
end
Was it helpful?

Solution

You would have to explicitly generate a model; it doesn't happen as a by-product of creating a join table.

A has_and_belongs_to_many association doesn't actually need a model class representing the association. It is supposed to be just a join table so what you've set up is exactly right.

The other option for such associations is a has_many through: association which uses an intermediate, or join, class. This is discussed in more details in the rails guide for associations. You would have to generate that joining model yourself though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top