Answer the question
In order to leave comments, you need to log in
Why do has_one and has_many work differently?
Good evening.
I do the following for has_many:
rails g model Author name:string (has_many :books - added to the model)
rails g model Book title:string author:references (belongs_to :author - created automatically in the model)
rails db:migrate
I go to the rails console and I execute:
Author.create! name: 'Name'
Author.first.books.create! title: 'Hello i title!!!'
Everything is working.
I do the following for has_one
rails g model User name:string (has_one :profile - added to the model)
rails g model Profile about:string user:references (belongs_to :user - created automatically in the model)
rails db:migrate
I go to the rails console and execute :
User.create! name: 'Name' (first user created successfully)
User.first.profile.create! about: 'hello world' (not created)
Why does this behavior work with has_many association but with has_one?
How do I create 1 to 1, what's wrong?
Answer the question
In order to leave comments, you need to log in
Added methods for has_many and for has_one
user = User.create! name: 'Name'
user.create_profile! about: "hello world"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question