我目前有两个模型,List
和 Item
:
class List < ApplicationRecord
has_and_belongs_to_many :items
end
class Item < ApplicationRecord
has_and_belongs_to_many :lists
end
每个列表 has_and_belongs_to_many
项和每个项 has_and_belongs_to_many
通过 items_lists
连接表列出。
目前,我可以使用以下代码将项目添加到列表中:
list.items.new(id: item.id)
这工作正常,但我想在将项目添加到列表时指定该项目的数量。
因此,在连接表中,我添加了另一个名为 quantity
的列,该列应该存储显示需要多少项目的数量。添加数量列后,我尝试使用以下代码将数量与项目一起保存:
list.items.new(id: item.id, quantity: 3)
但是,我收到一条错误消息:ActiveModel::UnknownAttributeError:项目的未知属性“数量”。
由于我尝试的方式似乎不正确,应该怎样做才能将一定数量的项目添加到列表中?
最佳答案
您需要使用has Many through
关系,而不是has and属许多
。这将涉及更改两个现有模型的关系以及创建第三个模型。您希望将此关系用于多对多,因为您除了存储两个记录主键之外还存储数据(has_many_through 文档)
class List < ApplicationRecord
has_many :items_lists
has_many :items, through: :items_lists
end
class Item < ApplicationRecord
has_many :items_lists
has_many :lists, through: :items_lists
end
class ItemsList < ApplicationRecord
belongs_to :item
belongs_to :list
end
此外,您的 items_lists
表应具有 list_id
和 item_id
。所以你最终会打电话
list.items.new(item_id: item.id, quantity: 3)
关于ruby-on-rails - Ruby on Rails 将表与数量连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38315806/