首页 > 解决方案 > 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

标签: ruby-on-railsactiverecordmany-to-many

解决方案


需要进行一些更正:

添加在;class_name_:product_ordersOrder

class Order < ApplicationRecord
  belongs_to :user
  has_many :product_orders, class_name: 'ProductOrders'
  has_many :products, through: :product_orders
end

belongs_to应该有单数orderproduct

class ProductOrders < ApplicationRecord
  belongs_to :order
  belongs_to :product
end

推荐阅读