GIZ! Blog

Menambah Foreign Key/References Dengan File Migrasi

Menambah foreign key atau references dengan file migrasi pada Rails 4.x

— Mar 13, 2015 —

Di Rails 4.x bisa dengan References

rails g migration AddLinkRefToArticles link:references

File migrasi yang terjadi

class AddLinkRefToArticles < ActiveRecord::Migration
  def change
    add_reference :articles, :link, index: true
    add_foreign_key :articles, :links
  end
end

Jika benar, di schema.rb bertambah field dan index

t.integer  "link_id"
add_index "articles", ["link_id"], name: "index_articles_on_link_id"

Jangan lupa nambah relasi di model.

MISC Links

https://stackoverflow.com/questions/16257116/adding-foreign-key-to-a-rails-model