I would like to add to these good answers that if you required dm-constraints (either directly or via data_mapper ) and use auto_migrate! , then belongs_to will automatically add foreign key constraints at the database level, while has will not.
eg:.
require 'data_mapper' class Post include DataMapper::Resource property :id, Serial end class Comment include DataMapper::Resource property :id, Serial belongs_to :post end
Produces this (via the MySQL adapter):
~ (0.140343) CREATE TABLE comments (id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, post_id INT(10) UNSIGNED NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci ~ (0.234774) CREATE INDEX index_comments_post ON comments (post_id) ~ (0.433988) ALTER TABLE comments ADD CONSTRAINT comments_post_fk FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE NO ACTION ON UPDATE NO ACTION
If you use has n, :comments belongs_to :post has n, :comments inside Post , but do not include belongs_to :post inside Comment , the post_id column in the comments table will still be created and indexed, but no foreign key constraint will be added.
source share