Search code examples
ruby-on-railsrubyactiverecordassociationsruby-on-rails-6

Rails 6: How to delete an element from a not-yet-persisted ActiveRecord Associations CollectionProxy?


Suppose the following model situation:

class Library < ApplicationRecord
  has_many :books
end

How would I correct the below deletion command (which is wrong because @library.books is not a Ruby Array but a Rails ActiveRecord Associations CollectionProxy)?

@library.books.delete_if {|book| book.page_count < 100}
@library.save

Note:

@library and @library.books are not-yet persisted in the database (thus, they don't have IDs yet).

The deletion should not touch the database, but happen exclusively in the ActiveRecord Associations CollectionProxy before it is persisted in the database using @library.save.


Solution

  • I suggest reassigning books collection:

    @library.books = @library.books.select { |book| book.page_count >= 100 }