Mongoid,子模型没有创建
Mongoid, Child Models are not creating
我有两个模型 Owner
和 Shop
:
class Owner
include Mongoid::Document
include Mongoid::Timestamps
# Fields
field :name, type: String
# Associations
has_many :shops, dependent: :destroy
accepts_nested_attributes_for :shops
# Validations
validates_presence_of :name
end
class Shop
include Mongoid::Document
include Mongoid::Timestamps
# Fields
field :name, type: String
field :address, type: String
belongs_to :owner
# Validations
validates_presence_of :name, :address, :owner
end
现在我尝试创建所有者
2.times do
owner = Owner.create(name: Faker::Name.name)
owner.save
3.times do
shop = Shop.create
shop.name = Faker::Company.name
shop.owner = owner
shop.address = "#{Faker::Address.street_address} #{Faker::Address.building_number}"
shop.save
end
owner.save
end
当我开始这个的时候。它创建所有者但不创建其商店。不知道为什么?
由于验证而未创建,请尝试 Shop.new
而不是 Shop.create
2.times do
owner = Owner.new(name: Faker::Name.name)
if owner.save!
3.times do
shop = Shop.new
shop.name = Faker::Company.name
shop.owner = owner
shop.address = "#{Faker::Address.street_address} #{Faker::Address.building_number}"
shop.save!
end
end
end
我有两个模型 Owner
和 Shop
:
class Owner
include Mongoid::Document
include Mongoid::Timestamps
# Fields
field :name, type: String
# Associations
has_many :shops, dependent: :destroy
accepts_nested_attributes_for :shops
# Validations
validates_presence_of :name
end
class Shop
include Mongoid::Document
include Mongoid::Timestamps
# Fields
field :name, type: String
field :address, type: String
belongs_to :owner
# Validations
validates_presence_of :name, :address, :owner
end
现在我尝试创建所有者
2.times do
owner = Owner.create(name: Faker::Name.name)
owner.save
3.times do
shop = Shop.create
shop.name = Faker::Company.name
shop.owner = owner
shop.address = "#{Faker::Address.street_address} #{Faker::Address.building_number}"
shop.save
end
owner.save
end
当我开始这个的时候。它创建所有者但不创建其商店。不知道为什么?
由于验证而未创建,请尝试 Shop.new
而不是 Shop.create
2.times do
owner = Owner.new(name: Faker::Name.name)
if owner.save!
3.times do
shop = Shop.new
shop.name = Faker::Company.name
shop.owner = owner
shop.address = "#{Faker::Address.street_address} #{Faker::Address.building_number}"
shop.save!
end
end
end