ayushsrivastava
Wed Dec 18 2024
accepts_nested_attributes_for
is a Rails method that allows you to easily manage the creation, updating, and destruction of associated models through the parent model's attributes. This is particularly useful when you have nested forms or when you want to handle multiple models in a single operation (e.g., creating or updating a User
and its associated Profile
in one form submission).
class User < ApplicationRecord
has_one :profile
accepts_nested_attributes_for :profile
end
Given the
User
model has a has_one :profile
association, and you want to create or update a User
and their Profile
at the same time, you can use accepts_nested_attributes_for
to pass attributes for both models:
user_params = {
name: "John Doe",
profile_attributes: { bio: "Developer", age: 30 }
}
user = User.create(user_params)
In this example, Rails will create both a new
User
and a new Profile
with the attributes provided in profile_attributes
.#CU6U0R822