Why am I getting 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 connection table stopped working. If I do @order.line_items , it throws an exception "Unknown primary key for line_items table in LineItem model". @order.products works as expected.

I tried to delete and recreate the line_items table, and I tried to set the protected_attributes gem, but nothing changed.

Here is the trace .

+6
source share
5 answers

In the model add

 self.primary_key = [:order_id, :product_id] 

and I think it would be wise to ensure that there is an index on these columns. You can create it with subsequent migration

 add_index :line_items, [:order_id, :product_id] 
+12
source

id: false in the source schema indicates that there is no id field in the table. Rails 4 added a create_join_table helper method that creates tables without an id field and uses this for any migration with JoinTable in the name.

The only way to imagine that you get results with Rails 4 than with Rails 3 is to restore your migrations and migrate with JoinTable in the name. Do you still have a schema from Rails 3? It would be interesting to note that for the connection table has id: false .

As with primary_key, the reason you could set the primary key to an array but didn't work afterwards is because the primary_key= method blindly converts your argument into a string on line 115 https://github.com/rails/rails /blob/a0dfd84440f28d2862b7eb7ea340ca28d98fb23f/activerecord/lib/active_record/attribute_methods/primary_key.rb#L115

See also fooobar.com/questions/949373 / ... and its links.

+7
source

The accepted answer got rid of the error message, but I still could not save @ order.line_items without receiving the error, saying that [: order_id ,: product_id] does not exist.

Finally, I 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 did not use β€œlinks” when I created the table initially that Rails 3 did not mind, but made Rails 4 complaints.

+2
source

Removing id: false should fix your error. To do this, migrate with the following line:

add_column :model, :id, :primary_key

+1
source

I had this error, but I deleted my local database using rake db:drop and then created using rake db:create before running pg_restore when the db hero dump solved it.

0
source

Source: https://habr.com/ru/post/949368/


All Articles