Rails PG::UndefinedColumn: ERROR: column carts_parts.[:part_id, :cart_id] does not exist

Rails PG::UndefinedColumn: ERROR: column carts_parts.[:part_id, :cart_id] does not exist

看来我又一次 运行 遇到了另一个与我加入的关联有关的问题 table。我有一个连接 table CartsParts,它用于 Carts 和 Parts 之间的多对多关系。关系是一个用户有一个购物车,一个购物车有很多部分,但是一个部分有很多并且属于购物车,因为多个用户可以有一个购物车。我的连接 table 有一个 cart_id 和一个 part_id。设置迁移后,我看到了这个错误:

这是我的零件模型

class Part < ActiveRecord::Base
  has_many :order_items
  has_and_belongs_to_many :carts, through: :carts_parts
  has_many :carts_parts

购物车模型

class Cart < ActiveRecord::Base
  has_many :order_items
  belongs_to :user
  has_many :carts_parts 
  has_many :parts, through: :carts_parts

CartsPart 模型

class CartsPart < ActiveRecord::Base
  has_many :parts
  has_many :carts
  self.primary_key = [:part_id, :cart_id]

CartsPart table

 create_table "carts_parts", id: false, force: :cascade do |t|
    t.integer "cart_id", null: false
    t.integer "part_id", null: false
  end

购物车Table

 create_table "carts", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
  end

和我的零件 Table

create_table "parts", force: :cascade do |t|
    t.string  "name"
    t.text    "description"
    t.integer "category_id"
    t.integer "price"
    t.boolean "active"
    t.integer "discount"
    t.string  "image"
    t.integer "quantity"
    t.integer "carts_part_id"
  end

感谢您帮助解决此问题

你做的太多了。 habtm 模式在很大程度上依赖于惯例。甚至连接 table 中的名称顺序也很重要。只要您 follow the conventions as described 就不需要定义 through 关系,也不需要定义主键。从你的模型中去掉这些东西,它应该开始工作了。