Я хочу реализовать 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