Why do I get an Unknown Primary Key exception for a join table in Rails 4?

后端 未结 5 604
情歌与酒
情歌与酒 2021-01-04 09:21

These are my models:

class Product
  has_many :line_items
  has_many :orders, :through => :line_items
end

class LineItem 
  belongs_to :order
  belongs_t         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 09:57

    The accepted answer got rid of the error message, but I was still unable to save @order.line_items without getting an error telling me [:order_id, :product_id] does not exist.

    I finally solved this by deleting the line_items table and recreating it with this migration:

      def change
        create_table :line_items do |t|
          t.references :order
          t.references :product
          t.integer :quantity
          t.timestamps
        end
      end
    

    I hadn't used "references" when I created the table originally, which Rails 3 didn't mind, but made Rails 4 complain.

提交回复
热议问题