Last active
September 18, 2016 18:57
-
-
Save kirs/e99bc45e2afb9f09c075013a081e6e69 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# runs on Rails 5 master / 831f1b67b741ee7a8af070ab18975ecdde4a9a69 | |
require 'bundler/setup' | |
require 'active_record' | |
ActiveRecord::Base.establish_connection(adapter: 'mysql2', database: 'after_commit_test') | |
ActiveRecord::Schema.define do | |
%w(shops api_permissions api_clients).each do |table| | |
if table_exists?(table) | |
drop_table(table) | |
end | |
end | |
create_table "shops" do |t| | |
t.string "name" | |
end | |
create_table "api_permissions" do |t| | |
t.integer "shop_id" | |
t.integer "api_client_id" | |
end | |
create_table "api_clients" do |t| | |
t.boolean "is_deleted", default: 0 | |
t.integer "shop_id" | |
end | |
end | |
class ApiClient < ActiveRecord::Base | |
has_many :api_permissions, inverse_of: :api_client | |
belongs_to :shop | |
end | |
class Shop < ActiveRecord::Base | |
# removing `includes(:api_client)` solves the problem | |
has_many :api_permissions, -> { includes(:api_client).joins(:api_client).where('api_clients.is_deleted = 0') }, dependent: :destroy, inverse_of: :shop | |
has_many :api_clients, :dependent => :nullify | |
end | |
class ApiPermission < ActiveRecord::Base | |
belongs_to :api_client, :inverse_of => :api_permissions | |
belongs_to :shop, inverse_of: :api_permissions | |
after_commit :log_shop, on: :destroy | |
def log_shop | |
puts shop.name | |
# will raise with | |
# undefined method `name' for nil:NilClass (NoMethodError) | |
end | |
end | |
shop = Shop.create! | |
client = ApiClient.create!(shop: shop) | |
ApiPermission.create!(shop: shop, api_client: client) | |
shop.destroy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment