Rails 4.2 Foreign Key Support

Updated . Posted . Visible to the public.

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

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
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2015-07-28 14:53)