- Published: August 18, 2016
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.
Having the following models
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
@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
@user = User.create(name: "John") @article = @user.articles.build(content: "Foobar")