1
votes

I have a newbie rails question. I'm trying to make sure a model has at least one association via a HABTM relationship. Basically I have created the following validation:

validate :has_tags?
def has_tags?
    errors.add(:base, 'Must have at least one tag.') if self.tags.blank?
end

This works fine when I create a new record. The problem is when I take the model and try to remove the association, doing something like this:

tag = Tag.find(params[:tag_id])$
@command.tags.delete(tag)$

It is permitted, i.e. the association will be deleted. Based on my reading on HABTM associations (http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association), I should "use has_many :through if you need validations, callbacks, or extra attributes on the join model."

I guess my question is how to perform validation on the .delete method for an association. Should I do this manually when I call delete (i.e. run a separate join to count the number of associations before executing a delete), or is there a way to use a validation model when deleting? Here is my model:

class Command < ActiveRecord::Base
  has_many :tagmapsorters
  has_many :tags, through: :tagmapsorters
  validates :text, presence: true
  validates :description, presence: true
  validates :text, uniqueness: true
  validate :has_tags?
  def has_tags?
    errors.add(:base, 'Must have at least one tag.') if self.tags.blank?
  end
end

I appreciate you taking the time to help me.

Dan

1

1 Answers

1
votes

Any callbacks that you need should be registered as before_destroy (for validations) or after_destroy (for cleanup) on the join model Tagmapsorter, as that is the record that is actually being destroyed.