开发者

Rails 3 single table inheritence w/ has_many question

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


Try renaming :type to something else, like :article_type

eg:

t.string      :article_type,      :null => false    # for STI


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜