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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)