The Idiomatically Correct Way To Make An Instance Of A Many To One Relationship Model
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
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
- The Idiomatically Correct Way To Make An Instance Of A Many To One Relationship Model
- Simple Debugging In RailsAugust 12, 2016
- Common Steps To Start A Rails ProjectAugust 8, 2016
- Building A Hello World App In Ruby On Rails AppAugust 7, 2016
- Ruby On Rails OverviewAugust 7, 2016
Articles
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
·