Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Deleting unsaved associated records

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

like image 908
Matthew Hui Avatar asked Jan 03 '13 07:01

Matthew Hui


People also ask

What is the difference between delete and destroy in rails?

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.

What is soft delete in Rails?

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.


2 Answers

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
like image 189
Robert Avatar answered Sep 18 '22 15:09

Robert


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.

like image 37
pdu Avatar answered Sep 16 '22 15:09

pdu