Mongoid/Rails has_and_belongs_to_many 在循环中返回 true - 为什么?

Mongoid/Rails has_and_belongs_to_many returning true in loop - why?

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

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 关系。所有工作都按预期进行,同时 saving/retrieving 数据:

@products = Products.all

这将 return 这个 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
        ...

这将 return 按预期显示类别名称。我遇到的问题是,虽然上面的代码将按预期 return 类别,但它也会在它的末尾打印 true (如果是上面的对象):

Category 1true

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

正如@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