Single Table Inheritance and Validations

Hi All,

I have my models as so:

class Asset < ActiveRecord::Base
validates_presence_of :title, :file, :class_name
set_inheritance_column ‘class_name’
end

class DocumentAsset < Asset
validates_presence_of :description
end

So a DocumentAsset has additional validations. But when I create and
save a new record (with params[:asset][:class_name] being
‘DocumentAsset’) in my controller:

def create
@asset = Asset.new()
@asset.attributes = @asset.attributes.merge(params[:asset])
if @asset.save
flash[:notice] = ‘Asset was created.’
redirect_to asset_list_url
else
render :action => ‘new’
end
end

It gets past the validations, even if the params[:asset][:description]
is nil.

Is this correct? If so, how can you specify custom validation for
subclasses of my Asset model.

Many Thanks,

Mark D.

You need to create an instance of the actual class. Since you’re
creating it
on Asset, the validations won’t fire.

You’ll need

  1. Determine what type to create and create it dynamically.

    asset_type = params[:asset][:class_name]

    do something here to restrict what type of asset you’re dealing

with… we don’t want them hacking
# your system because the next line instantiates a class based off
of
the string!

 @asset = asset_type.constantitze.new

Or

  1. Put all validations on Asset and then run them conditionally with the
    :if
    option.

    validates_presense_of :description, :if=> :is_a_document?

    def is_a_document?
    self.class_name == “Document”
    end

Brian,

Many thanks - that’s great!

Cheers,

Mark