I currently have two models, List
and Item
:
class List < ApplicationRecord
has_and_belongs_to_many :items
end
class Item < ApplicationRecord
has_and_belongs_to_many :lists
end
Each list has_and_belongs_to_many
items and each item has_and_belongs_to_many
lists through the items_lists
join table.
Currently, I can add items to the list using the following code:
list.items.new(id: item.id)
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 quantity
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:
list.items.new(id: item.id, 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?
答案 0 :(得分:3)
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
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
additionally, your items_lists
table should have a list_id
and an item_id
. so you would end up calling
list.items.new(item_id: item.id, quantity: 3)