CJBrew
CJBrew

Reputation: 2787

Rails association has_one, through, dependent destroy does not destroy related objects

I can't find documentation in the Rails site that covers this particular use case. Presumably normal has_one will work (because it says so). I've not tried yet.

Given two models and a join table for the association, I would expect dependent: :destroy to cause the join table row to be deleted on destroying the parent model.

The chained deletion only works for a has_many relationship (this code not shown here, but it's easy to modify the models to achieve it).

I believe there would be a workaround based on using has_many with uniqueness constraints (possibly on the join table). But I don't think I should have to!

IRB to reproduce:

000 > a = ModelA.create(name: "Fruity")

( output )

001 > b = ModelB.create(interesting_thing: "Tennis")
( output )

002 > a.model_b = b
( output )

003 > pp ModelAModelB.all

  ModelAModelB Load (0.3ms)  SELECT "model_a_model_bs".* FROM "model_a_model_bs"
[#<ModelAModelB:0x005609f4fa5128
  id: 1,
  model_a_id: 1,
  model_b_id: 1,
  created_at: Fri, 27 Jan 2017 13:37:15 UTC +00:00,
  updated_at: Fri, 27 Jan 2017 13:37:15 UTC +00:00>]

004 > a.destroy

   (0.1ms)  begin transaction
  SQL (3.0ms)  DELETE FROM "model_as" WHERE "model_as"."id" = ?  [["id", 1]]
   (4.5ms)  commit transaction

Models:

class ModelA < ApplicationRecord
  has_one :model_a_model_b
  has_one :model_b, through: :model_a_model_b, dependent: :destroy
end

class ModelB < ApplicationRecord
  has_one :model_a_model_b
  has_one :model_a, through: :model_a_model_b, dependent: :destroy
end


class ModelAModelB < ApplicationRecord
  belongs_to :model_a
  belongs_to :model_b
end

Schema:

ActiveRecord::Schema.define(version: 20170127100855) do

  create_table "model_a_model_bs", force: :cascade do |t|
    t.integer  "model_a_id"
    t.integer  "model_b_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["model_a_id"], name: "index_model_a_model_bs_on_model_a_id"
    t.index ["model_b_id"], name: "index_model_a_model_bs_on_model_b_id"
  end

  create_table "model_as", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "model_bs", force: :cascade do |t|
    t.string   "interesting_thing"
    t.datetime "created_at",        null: false
    t.datetime "updated_at",        null: false
  end

end

Gemfile:

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Upvotes: 1

Views: 1911

Answers (1)

j-dexx
j-dexx

Reputation: 10406

You need to have dependent destroy on the join model too.

class ModelA < ApplicationRecord
  has_one :model_a_model_b, dependent: :destroy
  has_one :model_b, through: :model_a_model_b, dependent: :destroy
end

Or better yet, have foreign keys with on_delete: :cascade to get the database to delete them.

Upvotes: 2

Related Questions