我有两个模型,items和categories,它们使用has_and_belongs_to_many关联具有多对多的关系。
在我的模型中:
class Item < ActiveRecord::Base
has_and_belongs_to_many :categories
end
and
class Category < ActiveRecord::Base
has_and_belongs_to_many :items
end
我创建了一个联接表 "categories_items":
create_table "categories_items", :id => false, :force => true do |t|
t.integer "category_id"
t.integer "item_id"
end
我没有收到任何错误提示,但是我对关联允许的准确含义有点困惑。现在,如果我有一些类别 @category,我可以通过执行以下操作找到其中的所有项目:
@category.items
我假设可以通过以下方式找到与给定物品@item相关联的类别:
@item.categories
然而,我遇到了一个错误,显示为ActiveModel :: MissingAttributeError:缺少属性:category
我是否对has_and_belongs_to_many关联的函数有误解,或者我的代码有遗漏?谢谢!
编辑-附加信息:
我认为困惑在于我该如何分配项目/类别。目前,我是独立创建它们的:
@item = Item.new
... add attributes ...
@item.save
并且。
@category = Category.new
... add attributes ...
@category.save
并将它们与...关联起来。
@category.items << @item
@item.categories << @category
@item
是如何被赋值的? - x1a4select
限制返回的列数而引起的。在我遇到的情况中,几乎总是这个原因导致的。 - x1a4