例如,如果我们考虑两个模型,产品和品牌,我应该为每个模型中的每个关联文档的 id 声明一个字段吗?
class Product
include Mongoid::Document
field :name, :type => String
field :brand_id, :type => Moped::BSON::ObjectId
validates :name, presence: true
validates :brand_id, presence: true
belongs_to :brand
end
--
class Brand
include Mongoid::Document
field :name, :type => String
field :description, :type => String
field :product_id, :type => Moped::BSON::ObjectId
validates :name, presence: true, uniqueness: true
validates :product_id, presence:true
has_many :products
end
无论模型是否声明它们存在,这些字段brand_id
和product_id
都是自动创建的,因此无论是否包含它们,代码都可以正常工作。我只是好奇这种事情的标准做法是什么。