This project is archived and is in readonly mode.

#3964 ✓duplicate
Staszek

Destroy for association collection does not delete object from parent array

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

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>]
***

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages