如何实现has_and_belongs_to_many关联?

时间:2019-02-05 19:06:02

标签: ruby-on-rails ruby-on-rails-5

我想在两个模型和一个联接表之间实现has_and_belongs_to_many关联。这怎么可能?什么是路由声明和模型文件声明?

举个例子:一个国家可以有很多公司,而公司可以在很多国家。我可以这样做吗?

class Company < ApplicationRecord
    has_and_belongs_to_many :countries
end

class Country < ApplicationRecord
    has_and_belongs_to_many :companies
end

Rails.application.routes.draw do
    resources :countries do
       resources :companies 
    end

    resources :companies do
      resources :countries 
    end
end

class CreateCountries < ActiveRecord::Migration[5.2]
  def change
    create_table :countries do |t|
      t.string :name
      t.timestamps
    end
  end
end

class CreateCompanies < ActiveRecord::Migration[5.2]
  def change
    create_table :companies do |t|
      t.string :name
      t.timestamps
    end
  end
end

class CreateJoinTableCountryCompany < ActiveRecord::Migration[5.2]
  def change
    create_join_table :countries, :companies do |t|
       t.index [:country_id, :company_id]   
    end
  end
end

0 个答案:

没有答案