Search code examples
ruby-on-railspostgresqlforeign-keysrails-migrations

PG::DependentObjectsStillExist: ERROR: cannot drop column xxx_id of xxxxx because other objects depend on it


I'm trying to remove a foreign_key user_id from a table named subscriptions.

The model association is like

#user.rb

has_many :subscriptions
has_many :orders_through_vehicle, through: :subscriptions, source: :line_items
accepts_nested_attributes_for :subscriptions

and

  #subscription.rb

  # Indexes
  #
  #  idx_user_id (user_id)

  belongs_to :user, required: true

When I run the migration, remove_column :subscriptions, :user_id, it throws following errors:

PG::DependentObjectsStillExist: ERROR:  cannot drop column user_id of table subscriptions because other objects depend on it
DETAIL:  view vw_customer_size depends on column user_id of table subscriptions
view vw_subscriptions_daily_report depends on column user_id of table subscriptions
HINT:  Use DROP ... CASCADE to drop the dependent objects too.

I don't care about these Postgres views. Should I have to drop them as well, how do I do it using the rails migration?

Thank you


Solution

  • I'm able to fix the issue. Here I need to remove the two database views first,

        execute <<-SQL
          drop view if exists vw_customer_size
        SQL
    
        execute <<-SQL
          drop view if exists vw_subscriptions_daily_report
        SQL
    
        remove_column :subscriptions, :user_id