user.profile.name output if the profile exists?class User < ApplicationRecord has_one :profile end class Profile < ApplicationRecord belongs_to :user # attribute :name, :string end user = User.create(name: 'Alice') user.create_profile(name: 'Alice Profile') puts user.profile.name
The has_one association creates a method profile on User that returns the associated Profile object. Since the profile was created with name 'Alice Profile', user.profile.name returns that string.
profile.user after creation?profile.user.name output?class User < ApplicationRecord has_one :profile end class Profile < ApplicationRecord belongs_to :user end user = User.create(name: 'Bob') profile = user.create_profile puts profile.user.name
The belongs_to association on Profile creates a method user that returns the associated User. Since the profile was created from the user, profile.user.name returns 'Bob'.
has_one association where deleting the parent deletes the child. Which code is correct?The correct syntax uses a symbol for the option value: dependent: :destroy. Option B uses a string instead of a symbol, B misses the colon before destroy, and C uses the older hash rocket syntax incorrectly.
user.profile return nil unexpectedly?user.profile return nil even after creating a profile?class User < ApplicationRecord has_one :profile end class Profile < ApplicationRecord belongs_to :user end user = User.create(name: 'Carol') Profile.create(name: 'Carol Profile') puts user.profile
The profile was created without specifying the user_id, so it is not linked to the user. Therefore, user.profile returns nil.
build_profile twice on the same user?user.build_profile(name: 'First') then user.build_profile(name: 'Second') without saving. What is the state of user.profile.name?class User < ApplicationRecord has_one :profile end class Profile < ApplicationRecord belongs_to :user end user = User.create(name: 'Dave') user.build_profile(name: 'First') user.build_profile(name: 'Second') puts user.profile.name
Calling build_profile twice replaces the unsaved profile object. The last built profile is returned by user.profile, so the name is 'Second'.