Has_Many_Through Failing To Push a Many to a Through



我试图建立一个has_many_through关系,其中用户可以拥有一个带有项目的购物车。我可以为用户(chip.carts << chips_cart)添加购物车,但不能向购物车(chips_cart << coffee)推送商品。

我得到NoMethodError: undefined method& lt; & lt;"# & lt;购物车id: 5, user_id: nil>">

class User < ActiveRecord::Base
has_many :carts
has_many :items, through: :carts
end
class Cart < ActiveRecord::Base
belongs_to :user
has_many :items
end
class Item < ActiveRecord::Base
belongs_to :carts
has_many :users, through: :carts
end
chip = User.create(username: "Chip")
chips_cart = Cart.create
socks = Item.create(item: "socks", price: 5.00)

正如Hubert指出的,你有一个复数错误:

belongs_to :cart # not :carts

belongs_to/has_one关联的名称必须始终是单数。

你不需要使用铲操作符<<:

chip = User.create(username: "Chip")
chips_cart = chip.carts.create
socks = chips_cart.items.create(item: "socks", price: 5.00)

单个记录不响应<<。这就是为什么你会得到NoMethodError: undefined method <<' for #<Cart id: 5, user_id: nil>。如果你想使用铲操作符,你需要执行chips_cart.items << socks而不是chips_cart << socks

哦,甜蜜的语法糖

如果你真的想做chips_cart << socks,你可以实现<<方法:

class Cart < ApplicationRecord
# ...
def <<(item)
items << item
end
end

这是因为像Ruby中的许多操作符一样,shovel操作符实际上只是方法调用的语法糖。

class Item < ActiveRecord::Base
belongs_to :cart
...
end

最新更新