简体   繁体   中英

Rails unitialized constant error in many to many relationship

I am trying to create a relationship in which a user can have many orders and many products, an order can have many products but belong to one user, and a product can have many users and many orders.

So far I have the below code, with the three aforementioned models plus a join table. The issue I am having is that whenever I try accessing user.products for example, I get an uninitialized constant Order::ProductOrder error, or if I try product.orders I get uninitialized constant Product::Orders .

Would anyone be so kind as to lend their experience towards solving this problem?

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

DB Schema:

  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

Couple of corrections needed:

add class_name for :product_orders in Order ;

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

belongs_to should have singular order and product :

class ProductOrders < ApplicationRecord
  belongs_to :order
  belongs_to :product
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM