I have two associated models:
class HelpRequest < ActiveRecord::Base
has_many :donation_items, dependent: :destroy
accepts_nested_attributes_for :donation_items, allow_destroy: true
and
class DonationItem < ActiveRecord::Base
belongs_to :help_request
I have a validator that returns an error to the user if he/she tries to save a help_request
with no donation_items
.
validate :has_donation_items?
...
def has_donation_items?
if !self.donation_items.present?
errors.add :a_help_request, "must have at least one item."
end
end
I'm updating both the help_request
and the donation_items
from within a nested form in which the user can destroy single or multiple donation_items
. According to this, if the user destroys any donation_items
they shouldn't get destroyed in the database until the parent is saved. But I've verified that in my case, they're being destroyed immediately upon running the update_attributes
method. Here's stripped down code:
@help_request.update_attributes(help_request_params) # donation items get destroyed in the database right here
# do some stuff
if @help_request.save
#do some other stuff if the save is successful
Here's the help_request_params
with nested attributes:
def help_request_params
params.require(:help_request).permit(:id, :name, :description, :event_flag, :due_on_event, :date, :time, :send_notification, :event_id, :invoked, donation_items_attributes: [:id, :name, :amount, :_destroy])
end
Is there a reason why the database seems to be getting updated on update_attributes
?
Think I figured it out. update_attributes
saves (or attempts to) immediately. Instead, I've switched to assign_attributes
. Working out some other kinks, but it seems to have resolved the main problem.