-1

我有两个模型(产品和类别):

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 1true

那是什么?我怎样才能删除它?

4

1 回答 1

0

正如@phoet 所说,伪代码使我们无法确切知道发生了什么,但我猜你正在做一些简单的事情,比如输出循环的值,而不是静默循环并只输出类别。例如,请注意以下示例中的等号,除了嵌套输出之外,它还会输出对象本身的一些值:

在 ERB 中:

<%= for @products.each do |p| %>
  <%= p.categories.each do |c| %>
    <%= c.name %>
  <% end %>
<% end %>

对比

<% for @products.each do |p| %>
  <% p.categories.each do |c| %>
    <%= c.name %>
  <% end %>
<% end %>

在 HAML 中:

= for @products.each do |p|
  = p.categories.each do |c|
    = c.name

对比

- for @products.each do |p|
  - p.categories.each do |c|
    = c.name
于 2015-01-18T03:56:18.963 回答