views:

26

answers:

2

I've been trying to setup a Single Table Inheritance model in Rails 3 in which the parent class also contains a has_many relationship. Unfortunately I can't get it to work. Here are three classes as an example:

class Article < ActiveRecord::Base
    has_many :paragraphs, :dependent => :destroy, :autosave => true
end

class Paragraph < ActiveRecord::Base
    belongs_to :article
end

class SportsArticle < Article
end

And here's the migration that would be used to set this up:

class AddTables < ActiveRecord::Migration
    def self.up
        create_table :articles do |t|
            t.string      :type,      :null => false    # for STI
            t.string      :title,     :null => false
            t.timestamps
        end

        create_table :paragraphs do |t|
            t.references  :article,   :null => false
            t.timestamps
        end
    end

    def self.down
        drop_table :articles
        drop_table :paragraphs
    end
end

When I set it up this way and I try to create a new SportsArticle, say by doing the following:

SportsArticle.create(:title => "Go Giants")

I always get the following error:

"TypeError: can't convert String into Integer"

I have no idea how to fix this issue and have tried finding a solution online to no avail. Does anybody who has experience with STI models see anything wrong? Here's the link to the documentation on the create method if it will help in diagnosing the problem: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-create

A: 

Try renaming :type to something else, like :article_type

eg:

t.string      :article_type,      :null => false    # for STI
porkeypop
This didn't work. In the rails documentation it says you're supposed to name the column "type" to implement STI http://api.rubyonrails.org/classes/ActiveRecord/Base.html
Abe
Thanks for the response porkeypop, it did eventually end up being a naming collision of a different sort.
Abe
A: 

The error was being caused due to a naming collision. I was using a name for one of my models called "attributes" which was causing the problem. The hint that eventually diagnosed the problem came from the Rails Association Documentation.

Abe