The Idiomatically Correct Way To Make An Instance Of A Many To One Relationship Model

Published:
Last modified:
Tags Rails , Models , Web-Development

Overview

Having a many-to-one model relationship in Rails, an instance of such model can be manually made inserting the other model foreign id, but that is not the most natural way to express it in Rails.

The most common way to write such relationship in Rails is to create the related model through its association.

Example

Having the following models

graph LR; User--has_many-->Article;

then each Article would have an user_id foreign key.

Manually assign FK

The manually form for creating an Article instance with an associated User would be to create an User and assign its id to the Article’s user_id

@user = User.create(name: "John")
@article = Article.new(content: "Foobar", user_id: @user.id)

Create through association

Creating an article through the user instance would automagically set Article.user_id.

@user = User.create(name: "John")
@article = @user.articles.build(content: "Foobar")

Reference

Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus


Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme

·