views:

38

answers:

1

In ruby, you have an attribute called "type" which is the class of the object. Rails stores this at the database in a column called type. So, if I have several blog "types", I can do something like this

def create
  @blog = Blog.new(params[:blog])
  @blog[:type] = params[:blog][:type]
  # ...
end

If I add someone like this, and then load it, and ask its class (for instance, at the console), I have the right class name answered back.

However, when I save it afterwards, rails will run only the superclass validators, not the ones I defined in the subclass.

How should I make rails run the subclass validators?

A: 

blog.rb

class Blog < ActiveRecord::Base

  belongs_to :type

  validates_associated :type

  # you might also be interested in:
  # accepts_nested_attributes_for :type

end

blogs_controller.rb

class BlogsController < ApplicationController

  def create
    @blog = Blog.new(params[:blog])
    if @blog.save
      # ...
    end
  end

end
macek