I have a model Parent
class Parent < ApplicationRecord
has_many :jobs
accepts_nested_attributes_for :jobs, allow_destroy: true
end
and model Job
class Job < ApplicationRecord
belongs_to :parent
belongs_to :category
scope :for_category, ->(c) { joins(:category).where(category: { name: c }) }
validates :destination, presence: true
end
and the form looks like
= simple_nested_form_for @account, url: account_path, remote :true
= f.simple_fields_for :jobs, @jobs do |jobs_form|
= jobs_form.input :destination, as: :string
and the controller responsible looks like
class AccountsController < BaseController
before_action :fetch_jobs
def edit
end
def update
@account.update(account_params)
unless @account.valid?
render :edit
end
end
private
def fetch_jobs
@account.jobs.for_category(params['category'])
end
end
When the form is submitted, and the validation fails, I want to show those unsaved objects and the errors. But they are removed from @account object.
I have tried doing @account.assign_attributes to do @account.save later but even assign_attributes doesn't assign attribute for nested objects. I'm guessing the scope fetches it from database instead of the object's attribute in memory.
How can I keep the nested attribute in the @account object even though the validation failed so that I can show validation errors by highlighting the nested objects in view?