Nubtacular
Nubtacular

Reputation: 1397

Rails 4: Update Model Column on Destroy

This is for a ticketing system.

When you close a ticket, theres a column of resolution. The user types in the resolution, ie, "this ticket was resolved by xyz". The column is of type textfield, not a string. So you go to close it and type in some sort of resolution. But that field does not get 'updated' when the ticket is deleted.

Summary: update the column of resolution on the Ticket model when the ticket is destroyed. Reasoning: the resolution has to be passed to email (via Sendgrid) and SMS (via Twilio). Currently, it'll pass the default value of resolution (whatever that value may be when the ticket is created).

In the initial ticket creation form, I have resolution as a hidden field like so:

<%= f.hidden_field :resolution, :value => "No Resolution Provided" %>

What I've tried:

In the ticket.rb model:

before_destroy { self.update_attribute(:resolution, "a hardcoded value here") }

So sure that works but that isn't reading from the form, just a hardcoded value. Correct me if I'm wrong but what I'm attempting to do should be done in the controller, correct?

I've tried a before_action but haven't had much success. This method does not work when used with a before_action:

def update_resolution
    @ticket = Ticket.find(params[:id])
    @ticket_res = @ticket.resolution
    @ticket_res.update_attribute(params[:resolution])
end

The above creates a redirect loop.

What's the best way to go about this? Any and all input is appreciated.

Upvotes: 0

Views: 463

Answers (1)

Jon
Jon

Reputation: 10908

Updating a record just prior to deleting it just for some other function that doesn't actually need the record to work doesn't sound like a good way of working to me.

This workflow makes more sense to me:

  1. Submit form to controller for resolved ticket, with resolution text
  2. Create a background email job with details of the resolution to notify interested parties
  3. Create another background twilio job with the SMS detaios to notify interested parties
  4. Destroy the ticket (are you sure you won't ever need it again?)

You should read the Rails Guides on background jobs: http://guides.rubyonrails.org/active_job_basics.html

Whilst not the fastest background job system, delayed job will be the easiest to get started with - https://github.com/collectiveidea/delayed_job

Upvotes: 1

Related Questions