CodexBloom - Programming Q&A Platform

Rails 6.1: implementing callbacks and nested hash attributes in form submissions

👀 Views: 10 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-19
ruby rails activerecord callbacks Ruby

I've been struggling with this for a few days now and could really use some help... I'm performance testing and Hey everyone, I'm running into an issue that's driving me crazy. I'm currently working with an scenario with nested attributes not triggering the expected `before_save` callback in my Rails 6.1 application. I have a `Project` model that accepts nested attributes for `Tasks`. The `Project` should validate the presence of its `name` attribute, and I also have a callback defined to set a default value for `status` before the project is saved. Here's the relevant code for my models: ```ruby class Project < ApplicationRecord has_many :tasks, dependent: :destroy accepts_nested_attributes_for :tasks before_save :set_default_status validates :name, presence: true private def set_default_status self.status ||= 'pending' end end class Task < ApplicationRecord belongs_to :project validates :description, presence: true end ``` In my controller, I'm permitting nested attributes like this: ```ruby class ProjectsController < ApplicationController def create @project = Project.new(project_params) if @project.save redirect_to @project, notice: 'Project was successfully created.' else render :new end end private def project_params params.require(:project).permit(:name, tasks_attributes: [:description]) end end ``` When I submit the form without a `name`, I expect the validation to kick in, but instead, I see that the `before_save` callback is still executing, and the `status` is being set to 'pending'. This is confusing because I would expect the save process to halt if validations unexpected result. Additionally, when I try to submit the form with valid attributes, the `status` is not being set as expected if I also include a nested task. Is there something I'm missing in how nested attributes interact with callbacks in Rails? How can I ensure that the validation works as intended and the callback behaves correctly in this scenario? I'm coming from a different tech stack and learning Ruby. The project is a web app built with Ruby. Cheers for any assistance! I recently upgraded to Ruby 3.10. How would you solve this?