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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)