Lets say I have a user model that has many articles.
If I call user.articles.new many times I will have many unsaved article objects associated with the user. They are visible when you run user.articles. Calling user.save will save all of this unsaved records.
How can I delete unsaved records? I plan on calling user.save but I don't want those unsaved records to be there
Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.
Deleting something from your database is very common and handled very easily by rails as part of a CRUD action. In some cases, it is useful to create a “soft delete”, meaning that the deleted element will still exist in the database but won't appear to the user.
I use the following workaround before_validation :remove_blank_articles!
:
class User
has_many :articles
validates_associated :articles
before_validation :remove_blank_articles!
private
def remove_blank_articles!
self.articles = articles - articles.select(&:blank?)
true
end
end
class Article
belongs_to :user
validates_presence_of :title, :body
def blank?
title.blank? and body.blank?
end
end
An option would be user.articles.delete_if{|a| a.new_record?}
, but this sounds like a workaround for the actual problem, to which @regulatethis points in your question's comment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With