Posted over 4 years ago. Visible to the public. Repeats.

Don't forget: Automatically remove join records on has_many :through associations

Bad

Copy
# Given the following models class Image < ActiveRecord::Base has_many :album_image has_many :albums, through: :album_images end class Album < ActiveRecord::Base has_many :album_image has_many :images, through: :album_images end # Join model class AlbumImage < ActiveRecord::Base belongs_to :album belongs_to :image end

Destroying a record in this setup will only remove the record itself, and leave orphaned join records behind.

Copy
image = Image.last image.destroy # removes only the `image` record, # but none of the associated `album_image` join records

Good

By adding the :dependent => :destroy option to the has_many :through associations, the join records will be removed when an image or an album is destroyed.

Copy
class Image < ActiveRecord::Base has_many :album_image has_many :albums, through: :album_images, dependent: :destroy end class Album < ActiveRecord::Base has_many :album_image has_many :images, through: :album_images, dependent: :destroy end

Note: the associated record with through (the albums in the example) will never be deleted by specifying dependent: :destroy, only the join records. Thus the following example will have the same effect as the above and is more explicit:

Copy
class Image < ActiveRecord::Base has_many :album_image, dependent: :destroy has_many :albums, through: :album_images end

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Thomas Klemm
Last edit:
8 months ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Thomas Klemm to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more