基本Rails问题 - 如何在数据库中创建新条目?

Mis*_*hko 2 ruby-on-rails ruby-on-rails-3

我有以下型号:

Product: name, shop_id (foreign key), brand_id (foreign key), price
Shop:    name
Brand:   name
Run Code Online (Sandbox Code Playgroud)

协会是:

Product: belongs_to :shop
         belongs_to :brand
Shop:    has_many   :products
         has_many   :brands,   :through => :products
Brand:   has_many   :products
         has_many   :shops,    :through => :products
Run Code Online (Sandbox Code Playgroud)

问题1

这些关联是否有意义?你会添加其他协会吗?

问题2

我想预先填充数据库db/seeds.db.

要添加ShopBrand我做:

Shop.create(:name => shop_name)
Brand.create(:name => brand_name)
Run Code Online (Sandbox Code Playgroud)

什么是最合适的添加方式Product?我真的需要手动插入shop_idbrand_id值吗?如果商店和新创建的产品的品牌尚不存在,它们会自动添加到数据库吗?

jdl*_*jdl 5

您所做的关联的一般想法是这样做:

shop = Shop.create(:name => shop_name)
shop.brands << Brand.create(:name => brand_name)
Run Code Online (Sandbox Code Playgroud)

或者相反.如果您不想,则不必手动创建连接模型.

编辑:以下是关于您的评论的演示.

设置迁移.

$ ./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
Run Code Online (Sandbox Code Playgroud)

模特.

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
Run Code Online (Sandbox Code Playgroud)

考试.请注意,没有任何代码行显式创建产品.

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
Run Code Online (Sandbox Code Playgroud)