has one

suggest change

A 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents