emersonthis
emersonthis

Reputation: 33348

Rails 4: self.update not working inside model

I'm trying to set up a simple soft delete system by adding a before_destroy callback which sets the deleted flag and then returns false (to prevent real destroy from happening).

class Project < ActiveRecord::Base

    belongs_to :user

    before_destroy :soft_delete

    def soft_delete
        self.update( is_deleted: 1 )
        false
    end

end

This does not result in the record getting updated. I'm not sure why. I see [1m[36m (0.4ms)[0m [1mROLLBACK[0m in my logs, but I'm not sure it's relevant or not.

Upvotes: 1

Views: 4917

Answers (4)

Roshan
Roshan

Reputation: 915

Try self.update_attributes(is_deleted: 1)

Worked for me on Rails 4.2.4

Upvotes: 2

derekyau
derekyau

Reputation: 2946

I would suggest overriding the destroy method directly in the controller. As always, try to follow rails' best practice of "Fat model skinny controller". I'd make the bulk of the logic in the Model, and then simply call it from the controller like this:

In your model:

def soft_delete!
    update_attribute(:is_deleted, 1)
    #remove any other attributes you want here (ie. if there are tasks associated with projects and such they should also be cascade "soft deleted here"
end 

In your controller:

def destroy
   @project = Project.find(params[:id])
   @project.soft_delete!
   redirect_to projects_path
end

Something like that would work - on top of this, you may want to:

  • Make soft_delete return boolean value so you can switch on it in controller and redirect to other places
  • Soft delete other related attributes in other models (where I added the comment)

Upvotes: 0

spickermann
spickermann

Reputation: 106782

I guess self.update_columns(is_deleted: true) may work...

Upvotes: 3

Lazarus Lazaridis
Lazarus Lazaridis

Reputation: 6029

Look here

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

Upvotes: 1

Related Questions