【问题标题】:Ruby on Rails Join Table with QuantityRuby on Rails 使用数量连接表
【发布时间】:2016-07-11 20:37:47
【问题描述】:

我目前有两个型号,ListItem

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: unknown attribute 'quantity' for Item.

由于我尝试的方式似乎不正确,应该怎么做才能允许将一定数量的项目添加到列表中?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-activerecord


    【解决方案1】:

    您需要使用has many through 关系而不是has and belongs to many。这将涉及更改两个现有模型的关系以及创建第三个模型。您希望将此关系用于多对多,因为除了两个记录主键之外,您还要存储数据(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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-10
      • 2011-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 2011-05-28
      • 2010-10-20
      相关资源
      最近更新 更多