ruby-on-rails - Rails在多对多关系中统一了常量错误
问题描述
我正在尝试创建一种关系,其中一个用户可以有很多订单和很多产品,一个订单可以有很多产品但属于一个用户,一个产品可以有很多用户和很多订单。
到目前为止,我有下面的代码,上面提到的三个模型加上一个连接表。我遇到的问题是,每当我尝试访问时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
解决方案
需要进行一些更正:
添加在;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
推荐阅读
- python - 所有机器都忙时的标志列?
- android - Android 9.0 在主线程上创建套接字会导致 android.os.NetworkOnMainThreadException
- excel - ListView 中的图标
- angular - 您如何在 Ionic/Angular 中处理应用程序版本控制服务器端?- APP_BASE_HREF 与路由冲突
- sbt - 代码在 zepplin 上运行良好,但在使用 sbt 编译后无法使用 spark-submit
- azure - Azure IOT Edge 设备能否连接到多个 Azure IOT Hub?
- dictionary - 增加可变映射值会导致可为空的接收器错误
- c# - 将连字字符放入 ComboBox 文本
- reactjs - Redux 表单无法输入
- java - 创建一个将采用 jsonPath 和类型的验证,检查 jsonpath 和类型的数据类型是否相同