Общая идея с вашими ассоциациями заключается в следующем:
shop = Shop.create(:name => shop_name)
shop.brands << Brand.create(:name => brand_name)
Или наоборот. Вам не нужно вручную создавать модель соединения, если вы не хотите.
Редактировать: Ниже приведена демонстрация вашего комментария.
Настройка миграций.
$ ./script/rails g model Shop name:string
$ ./script/rails g model Brand name:string
$ ./script/rails g model Product brand_id:integer shop_id:integer
$ rm test/fixtures/*
$ rake db:migrate; rake db:test:prepare
Модели.
class Brand < ActiveRecord::Base
has_many :products
has_many :shops, :through => :products
end
class Shop < ActiveRecord::Base
has_many :products
has_many :brands, :through => :products
end
class Product < ActiveRecord::Base
belongs_to :brand
belongs_to :shop
end
Тест. Обратите внимание, что ни одна строка кода явно не создает продукт.
require 'test_helper'
class ShopTest < ActiveSupport::TestCase
def test_brand_assignment_to_shop
assert_equal 0, Product.count
shop = Shop.create(:name => "Foo Shop")
brand = Brand.create(:name => "Foo Brand")
shop.brands << brand
assert_equal 1, Product.count
assert_equal shop.id, Product.first.shop_id
assert_equal brand.id, Product.first.brand_id
end
end
$ ruby -I./test test/unit/shop_test.rb
Loaded suite test/unit/shop_test
Started
.
Finished in 0.029778 seconds.
1 tests, 4 assertions, 0 failures, 0 errors