e.g.
class Asset < ActiveRecord::Base
validates_presence_of :asset_number, :make, :model, :location,
:name, :serial_number
validates_numericality_of :asset_number
validates_uniqueness_of :asset_number
belongs_to :user
belongs_to :location
belongs_to :asset_type, :foreign_key => ‘type_id’
end
class Location < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name
has_many :assets
end
If I create a Location, with name ‘London’ and then create an Asset
with that location it makes sense for me to be able to delete the
asset but not to delete the location.
If the location is deleted I have a situation where the asset now has
a foreign key pointing to a non-existant record. In other words it
become orphaned.
I know that there are ways (in
http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html)
to make the foreign keys be set to null, or to delete all the orphans
(a bit like ON DELETE CASCADE), but what I want is to prevent the
delete of the location if it has assets which belong to it.
I was expecting some way to do this would be fairly easy and built
into AR but my hopes of that are fading… Hopefully it’s just that
I’ve missed something though.
If there is no way to do it that is built into AR how might I mod AR
or something to add that functionality? Presumably some kind of call
to location.assets.is_empty? to check if the delete is going to be
allowed?
-Rob
–
“On two occasions, I have been asked [by members of Parliament],
‘Pray, Mr. Babbage, if you put into the machine wrong figures, will
the right answers come out?’ I am not able to rightly apprehend the
kind of confusion of ideas that could provoke such a question.”
– Charles Babbage (1791-1871)
“98.5% of DNA is considered to be junk DNA with no known purpose.
Maybe it’s XML tags.” – Anon