Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Destroy for association collection does not delete object from parent array

#3964

We have normal one_to_many association

  class User < ActiveRecord::Base
    has_many :movies
  end
  
  class Movie < ActiveRecord::Base
    belongs_to :user
  end

Let's create user and some movies

user = User.create(:name => "user")
=> #<User id: 1, name: "user", movies_count: nil>
user.movies << [Movie.new(:name => "Titanic"), Movie.new(:name => "Matrix")]
=> [#<Movie id: 1, name: "Titanic", subject_type: "User", subject_id: 1>, #<Movie id: 2, name: "Matrix", subject_type: "User", subject_id: 1>]
titanic = @user.movies[0]
=> #<Movie id: 1, name: "Titanic", subject_type: "User", subject_id: 1>

Everything is ok now:

user.movies
=> [#<Movie id: 1, name: "Titanic", subject_type: "User", subject_id: 1>, #<Movie id: 2, name: "Matrix", subject_type: "User", subject_id: 1>]

After destroy

user.movies.destroy(titanic)
=> [#<Movie id: 1, name: "Titanic", subject_type: "User", subject_id: 1>, #<Movie id: 2, name: "Matrix", subject_type: "User", subject_id: 1>]
user.movies
=> [#<Movie id: 1, name: "Titanic", subject_type: "User", subject_id: 1>, #<Movie id: 2, name: "Matrix", subject_type: "User", subject_id: 1>]
It is not ok. Array contains destroyed movie. You need to reload object(make new database query)
user.reload.movies
=> [#<Movie id: 2, name: "Matrix", subject_type: "User", subject_id: 1>]
***

Reported by Staszek · February 15th, 2010 @ 01:19 PM

State: duplicate
Milestone: none
Assigned to: nobody
Importance: none