Read more

Rails 4.2 Foreign Key Support

Emanuel
July 28, 2015Software engineer at makandra GmbH

The migration DSL now supports adding and removing foreign keys. They are dumped to schema.rb as well. At this time, only the mysql, mysql2 and postgresql adapters support foreign keys. @rubyonrails Show archive.org snapshot

Workings

add_foreign_key(:comments, :users)

adds a database constraint

ALTER TABLE "comments" ADD CONSTRAINT comments_user_id_fk FOREIGN KEY ("user_id") REFERENCES "user" ("id")

Disadvantage

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Foreign key constraints double the validation logic. For most applications it's better to exclude things like default, 'not null' and foreign key constraints in the database. ActiveRecord supports most of them.

comment = Comment.build(title: 'Bikini Bottom', content: 'Burgers for free', user_id: 1)
comment.valid? => true
comment.save => ActiveRecord::InvalidForeignKey Exception
Posted by Emanuel to makandra dev (2015-07-28 16:53)