mGarsteck mGarsteck - 7 months ago 19
Ruby Question

after_destroy to remove categories

My code creates categories automatically upon creating a new instance of a model. Here is the code for one of the models.

class Grow < ActiveRecord::Base
belongs_to :category

after_create do
Category.create(name: self.title)
end

before_destroy do
Category.destroy(name: self.title)
end


end

The create works, but the destroy gives me this error

SQLite3::SQLException: no such column: id.name: SELECT "categories".* FROM "categories" WHERE "id"."name" = 'My very first grow room' LIMIT 1

Any ideas on how I can fix this problem?

Answer

Try this:

Category.find_by(name: self.title).destroy

Bear in mind that destroy will trigger any callbacks on the Category you have triggered by, but delete does not

This is what ActiveRecord (destroy) is doing under the hood:

# File activerecord/lib/active_record/base.rb, line 2614
  def destroy
    unless new_record?
      connection.delete(
        "DELETE FROM #{self.class.quoted_table_name} " +
        "WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quoted_id}",
        "#{self.class.name} Destroy"
      )
    end

    @destroyed = true
    freeze
  end