Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

These are my models:

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

class LineItem 
  belongs_to :order
  belongs_to :product
end

class Order
    has_many :line_items
    has_many :products, :through => :line_items
end

From schema.rb:

  create_table "line_items", id: false, force: true do |t|
    t.integer  "order_id"
    t.integer  "product_id"
    t.integer  "quantity"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

I just upgraded to Rails 4, and my join table stopped working. If I do @order.line_items, it throws the exception "Unknown primary key for table line_items in model LineItem." @order.products works as expected.

I have tried dropping and recreating the line_items table, and I have tried installing the protected_attributes gem, but nothing changed.

Here is the trace.

like image 741
lala Avatar asked Jul 13 '13 13:07

lala


2 Answers

In model add the following:

self.primary_key = [:order_id, :product_id]

and I think it would be wise to ensure that there's an index on those columns.

You may create one with following migration:

add_index :line_items, [:order_id, :product_id]
like image 74
Mike Szyndel Avatar answered Oct 21 '22 11:10

Mike Szyndel


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.

like image 27
lala Avatar answered Oct 21 '22 12:10

lala