I have a simple acts_as_list model structure where the Language holds
a lot of Wikis. I want to validate inside Wikis so as to not destroy
the last Wiki in a Language. However, when the Language is destroyed,
I want all the wikis associated with the Language to destroy
themselves.
The solution seemed simple until I figured out that when I try to
destroy a Language, the method fails at destroying the last Wiki.
This is because I am trying to destroy the last Wiki in the Language.
I need to, therefore, figure out a way to bypass the “last wiki
validations” ONLY when I’m destroying a Language. Is there a
conditional or a flag that lets me figure out that the parent is
trying to destroy the children?
Here’s my code, by the way:
class Language < ActiveRecord::Base
#indicate this is an array
has_many :wikis,
:order => :position,
:dependent => :destroy
#everything has to be unique!
validates_presence_of :language
validates_presence_of :url_id
validates_uniqueness_of :language
validates_uniqueness_of :url_id
validates_length_of :url_id,
:in => 2…5
validates_format_of :url_id,
:with => /^[a-z]{2}([a-z_]{0,2}[a-z])?$/
def after_update
if self.id == 1 and self.url_id != ‘en’
raise “Cannot change this language’s url!”
end
end
def after_destroy
if self.url_id == ‘en’
raise “Cannot delete this language!”
end
end
end
class Wiki < ActiveRecord::Base
#indicate this is array elements
belongs_to :language
acts_as_list :scope => :language_id
#general limits:
validates_presence_of :title
validates_format_of :title, :with => /^\w.+$/ #letter-first
validates_uniqueness_of :title, :scope => :language_id
validates_presence_of :body
validates_length_of :body, :minimum => 10