RSS
17 Jan 2007

Mimicking ON DELETE NO ACTION / RESTRICT in Active Record

Author: ceefour | Filed under: Beginner, Complaints, Opinions, Rails, Ruby, Tips, Web 2.0

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Active Record associations (has_many, has_one, belongs_to, has_and_belongs_to_many, etc.) only allows you to set :dependent as :destroy, :delete_all, or :nullify.

In the “real world”,some DBMSs (like PostgreSQL, which happen to be my favorite) allow you to have NO ACTION / RESTRICT during delete or update. Putting this on the DBMS will work most of the time. However, when you do testing with transactional fixtures, this will very likely cause problems. A failed statement will cause the transaction to “hang”, which can cause nasty error messages.

Besides, you want to handle these kinds of stuff in your Active Record model, don’t you? Here’s one quick way, use the “before_destroy” handler:

class Role :nullify # should be restrict

private
def ensure_no_users
raise ‘There are still users in this role.’ if !users.empty?
end
end

Note: You must put the “before_destroy” before the association (has_many). Otherwise it won’t work as advertised.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

blog comments powered by Disqus