user2367593 user2367593 - 10 months ago 62
Ruby Question

Ruby on Rails Join Table with Quantity

I currently have two models,


class List < ApplicationRecord
has_and_belongs_to_many :items

class Item < ApplicationRecord
has_and_belongs_to_many :lists

Each list
items and each item
lists through the
join table.

Currently, I can add items to the list using the following code:

This works fine, but I would like to specify a quantity of the item when it is added to the list.

So, in the join table, I added another column called
that should store a quantity that shows however many of the item is needed. After adding the quantity column, I tried the following code to save the quantity along with a item:, quantity: 3)

However, I received an error that said
ActiveModel::UnknownAttributeError: unknown attribute 'quantity' for Item.

Since the way I tried appears to be incorrect, what should be done to allow for a quantity of items to be added to a list?


you need to use a has many through relationship instead of the has and belongs to many. This will involve changing the relations on your two existing models as well as creating a third. You want to use this relationship for the many-to-many because you are storing data in addition to the two record primary keys (has_many_through documentation)

class List < ApplicationRecord
  has_many :items_lists
  has many :items, through: :items_lists

class Item < ApplicationRecord
  has_many :items_lists
  has many :lists, through: :items_lists

class ItemsList < ApplicationRecord
  belongs_to :item
  belongs_to :list

additionally, your items_lists table should have a list_id and an item_id. so you would end up calling, quantity: 3)