Rails migration for has_and_belongs_to_many join table

后端 未结 6 1421
花落未央
花落未央 2020-11-29 15:40

How do I do a script/generate migration to create a join table for a has_and_belongs_to_many relationship?

The application runs on Rails 2.

6条回答
  •  醉梦人生
    2020-11-29 16:44

    You should name the table the names of 2 models you want to connect by alphabetical order and put the two model id's in the table. Then connect each model to each other creating the associations in the model.

    Here's an example:

    # in migration
    def self.up
      create_table 'categories_products', :id => false do |t|
        t.column :category_id, :integer
        t.column :product_id, :integer
      end
    end
    
    # models/product.rb
    has_and_belongs_to_many :categories
    
    # models/category.rb
    has_and_belongs_to_many :products
    

    But this is not very flexible and you should think about using has_many :through

提交回复
热议问题