我有两个模型(产品和类别):
class Product
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :enabled, type: Boolean
field :price, type: BigDecimal
field :sku, type: String
field :editing, type: Boolean
field :supplier, type: String
has_and_belongs_to_many :categories
has_and_belongs_to_many :subcategories
validates :name, presence: true, uniqueness: true
validates :price, presence: true
end
class Category
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
field :editing, type: Boolean
field :enabled, type: Boolean
has_and_belongs_to_many :subcategories
has_and_belongs_to_many :products
validates :name, presence: true, uniqueness: true
end
如您所见,两者都有has_and_belongs_to_many
关系。在保存/检索数据时,所有工作都按预期工作:
@products = Products.all
这将返回这个json:
{
_id: ObjectId("54ba495957694d4d95010000"),
category_ids: [
ObjectId("54ba494557694d4d95000000")
],
created_at: ISODate("2015-01-17T11:36:57.641Z"),
enabled: false,
name: "Product 1",
price: "23.9",
sku: "KOPP0909",
updated_at: ISODate("2015-01-17T11:36:57.641Z")
}
到现在为止还挺好。在我看来,我将像这样遍历产品:
@products.each do |p|
p.categories.each do |c|
c.name
...
它将按预期返回显示类别名称。我遇到的问题是,虽然上面的代码将按预期返回类别(IES),但它也会true
在它的末尾打印(如果是上面的对象):
Category 1
和true
那是什么?我怎样才能删除它?