Active Record Inheritance
I have some issues in Rails Active Record Inheritance, I need to create a model that inherits parents class properties(fields) and should also hold its own properties.
Ex: Parent Class
class Content < ActiveRecord::Base
end
Classes inheriting parent class (Content)
class Wiki < Content // Inherting Class Content
end
class Video < Content // Inherting Class Content
end
Suppose "content" table contains fields type,name (to store common fields)
- "Wiki" table contains fields body,de开发者_开发百科scription
- "Video" table contains fields filename,description
Inserting into content and wiki table as
def create
WikiPage.new("name" =>"new_wikipage")
@wiki_page = WikiPage.new(params[:wiki_page])
end
but, the problem is the newly created wikipage is not inserting(because the parent class "Content" is abstracting child class Wikipage param values)
Generating Error like method "body" not defined (field "body" is part of wiki table,which got hided by content table)
Rails uses single-table inheritance (STI) for model subclasses. This means that you don't create a separate table for Wiki or Video in your database. They will all be stored in the "contents" table, and that table should include all the fields needed by all subclasses.
It's okay if not all subclasses use all the available fields. Rails then keeps track of what subclass a record is, using the "type" column of the parent table.
I walk through this in detail in this article called Single-Table Inheritance with Tests in Rails. I think the code samples will give you a better idea of how to proceed.
The technique you want to use is called Single Table Inheritance. Basically, only models which inherit directly from ActiveRecord::Base
have their own table. That table should have a type
column (required non-NULL) which stores the name of the class for each row/object.
You can read more about this in the Rails API docs. I've also written an article on when to use STI which might be helpful.
精彩评论