我正在尝试创建一种关系,其中用户可以有很多订单和许多产品,一个订单可以有很多产品但属于一个用户,并且一个产品可以有很多用户和很多订单。
到目前为止,我有以下代码,以及上述三个模型以及一个联接表。我遇到的问题是,例如,每当尝试访问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
答案 0 :(得分:1)
需要更正的夫妇:
在class_name
中为:product_orders
添加Order
;
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