gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:59:21 25 4
gpt4 key购买 nike

我有以下型号:

Product: name, shop_id (foreign key), brand_id (foreign key), price
Shop: name
Brand: name

这些协会是:

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

问题1

这些关联有意义吗?您会添加其他协会吗?

问题2

我想在 db/seeds.db 中预填充数据库。

要添加商店品牌,我这样做:

Shop.create(:name => shop_name)
Brand.create(:name => brand_name)

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

最佳答案

您所做的关联的总体思路是这样做:

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

关于ruby-on-rails - Rails 基本问题 - 如何在数据库中创建新条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4415305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com