JP Silvashy
JP Silvashy

Reputation: 48525

Rails, destroy if blank

This might sound odd, but is there a 'Rails way' to have a model destroyed if a certain attribute is blank? Say I have a model like tags with just a name attribute or something, if the user edits the tag and deletes all the text out of the name field in the form I'd like the model to just be deleted.

I'm aware of the reject_if method, but that doesn't seem to work.

Upvotes: 3

Views: 2953

Answers (1)

Dave Sims
Dave Sims

Reputation: 5128

On the after_save callback, just check the attribute and destroy the model if it's blank. Something like:

class Tag < ActiveRecord::Base
  after_save { |tag| tag.destroy if tag.name.blank? }
end

Upvotes: 8

Related Questions