has one
suggest changeA has_one association sets up a one-to-one connection with another model, but with different semantics. This association indicates that each instance of a model contains or possesses one instance of another model.
For example, if each user in your application has only one account, you’d declare the user model like this:
class User < ApplicationRecord
has_one :account
end
With has_one, Active Record treats one child row as the current association for that foreign key. Replacing it nullifies the previous row's foreign key when the new row is saved (unless you set dependent: :destroy). The database does not enforce that uniqueness unless you add a unique index.
user = User.first
user.build_account(name: "sample")
user.save # saves the user and creates an accounts row with this user_id
user.build_account(name: "sample1")
user.save # saves the new account and nullifies the previous account's user_id
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents