mGarsteck mGarsteck - 2 years ago 106
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)

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


The create works, but the destroy gives me this error

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

Any ideas on how I can fix this problem?

Answer Source

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?
        "DELETE FROM #{self.class.quoted_table_name} " +
        "WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quoted_id}",
        "#{} Destroy"

    @destroyed = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download