Home Rails 4.2: Turn a reference field into foreign key
Reply: 1

Rails 4.2: Turn a reference field into foreign key

Artur Haddad
1#
Artur Haddad Published in 2017-12-05 17:38:38Z

I'm maintaining an old system that uses Rails 4.2 and for an unknown reason the references are created this way:

  t.references :credit_card, null: false
  t.references :car, null: false
  t.references :profile, null: false

This allows me to create registers for this model with invalid credit_card ids, for example. Foreign key isn't validated.

Generating index migration didn't turn them into fk's and didn't validate them at all:

class AddIndexToRentals < ActiveRecord::Migration
  def change
    add_index :rentals, :credit_card_id
    add_index :rentals, :car_id
    add_index :rentals, :profile_id
  end
end

How can I make those fields foreign keys and accept only existent ids?

Joe
2#
Joe Reply to 2017-12-05 19:12:14Z

You can add a foreign key to your migration to validate existence of the referenced record, generate a migration and do the following.

class AddForeignKeyToRentals < ActiveRecord::Migration
  def change
    add_foreign_key :rentals, :credit_cards
    add_foreign_key :rentals, :cars
    add_foreign_key :rentals, :profiles
  end
end

One thing to note that you won't be able to run this migration if you have records that do not exist in the foreign key column. Also you can add an extra existence validation in your model.

validates :credit_card, :car, :profile, presence: true

Hope this helps! :)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323137 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO