Skip to content

Instantly share code, notes, and snippets.

@lirenyeo
Last active June 10, 2023 07:07
Show Gist options
  • Save lirenyeo/c73001d96411a9adb8a7a71c234e2984 to your computer and use it in GitHub Desktop.
Save lirenyeo/c73001d96411a9adb8a7a71c234e2984 to your computer and use it in GitHub Desktop.
Rails Nested Attributes vs Build from Association
class User < ApplicationRecord
has_many :posts
accepts_nested_attributes_for :posts, allow_destroy: true
has_one :profile
accepts_nested_attributes_for :profile
end
# To create nested records through the parent:
# Option 1: Nested Attributes
user = User.new(name: 'izumi', posts_attributes: [
{ title: 'first post' },
{ title: 'second poast' }
])
user.save
# Option 2: Building from the association
user = User.new(name: 'izumi')
user.posts.new([
{ title: 'first post' },
{ title: 'second post' }
])
user.save
# ----------------------------------------
# update, create and delete nested records at the same time
user = User.find_by(name: 'izumi')
user.update(name: 'izumi 2', posts_attributes: [
# update first post
{ id: 1, title: 'updated first post' },
# delete 2nd post
{ id: 2, _destroy: true },
# create 3rd post
{ title: 'new third post' }
])
# ----------------------------------------
# However, with has_one, we can't build from association:
user = User.new(name: 'miyaki')
user.profile.new # <=== error
# We have to use nested attributes:
user = User.new(name: 'miyaki', profile_attributes: { age: 20 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment