我正在尝试创建一种关系,在该关系中,用户可以拥有许多订单和许多产品,订单可以有许多产品但属于一个用户,并且产品可以有许多用户和许多订单。
到目前为止,我有下面的代码,其中包含上述三个模型以及一个连接表。我遇到的问题是,例如,每当我尝试访问user.products
时,我都会收到uninitialized constant Order::ProductOrder
错误,或者如果我尝试product.orders
,我就会uninitialized constant Product::Orders
。
有人会好心地为解决这个问题提供他们的经验吗?
class Order < ApplicationRecord
belongs_to :user
has_many :product_orders
has_many :products, through: :product_orders
end
class Product < ApplicationRecord
has_many :product_orders, class_name: 'ProductOrders'
has_many :orders, through: :product_orders
has_many :users, through: :orders
end
class User < ApplicationRecord
has_many :orders
has_many :products, through: :orders
end
class ProductOrders < ApplicationRecord
belongs_to :orders
belongs_to :products
end
数据库架构:
create_table "orders", force: :cascade do |t|
t.datetime "fulfilled_date"
t.integer "quantity"
t.integer "total"
t.bigint "user_id"
t.index ["user_id"], name: "index_orders_on_user_id"
end
create_table "product_orders", force: :cascade do |t|
t.bigint "product_id"
t.bigint "order_id"
t.index ["order_id"], name: "index_product_orders_on_order_id"
t.index ["product_id"], name: "index_product_orders_on_product_id"
end
create_table "products", force: :cascade do |t|
t.string "image_url"
t.string "name"
t.string "description"
t.integer "inventory", default: 0
t.integer "price"
t.bigint "order_id"
t.bigint "user_id"
t.index ["order_id"], name: "index_products_on_order_id"
t.index ["user_id"], name: "index_products_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.string "address"
t.string "state"
t.string "zip"
t.string "phone_number"
t.string "country"
end
需要更正几处:
在Order
中添加:product_orders
class_name
;
class Order < ApplicationRecord
belongs_to :user
has_many :product_orders, class_name: 'ProductOrders'
has_many :products, through: :product_orders
end
belongs_to
应该有单数order
和product
:
class ProductOrders < ApplicationRecord
belongs_to :order
belongs_to :product
end