Single Table Inheritance problem

I have two tables I am using single table inheritance with: Page and
Item. “Page” has many “Items”; “Item” belongs to “Page”.

Item Model:
class Item < ActiveRecord::Base
end

class Article < Item
belongs_to :page
end

Page Model:
class Page < ActiveRecord::Base
end

class Issue < Page
has_many :articles
end

In my controller, when I call @page.articles I am getting the following
problem:
Mysql::Error: #42S22Unknown column ‘items.issue_id’ in ‘where clause’:
SELECT * FROM items WHERE (items.issue_id = 4) AND ( (items.type =
‘Article’ ) )

I see exactly where the snafu is ‘items.issue_id’ should be
‘items.PAGE_id’ (caps for emphasis). I assume either I am setting up
the model incorrectly, or I’m trying to do something that’s not
supported. Everything else is exactly how I expect it.

Is there any way out of this hole?

On 5/10/06, Joe C. [email protected] wrote:

In my controller, when I call @page.articles I am getting the following
Is there any way out of this hole?
When you declare “has_many :articles”, you are expected to have a
foreign key in the articles table referring to the table backing the
ActiveRecord class you’re declaring it in. So, when you do so from
your Issue class (“has_many :articles”), ActiveRecord expects to see
an “issue_id” foreign key in your articles table. Nothing surprising
here.


Bosko M. [email protected]

On 5/10/06, Joe C. [email protected] wrote:

In my controller, when I call @page.articles I am getting the following
Is there any way out of this hole?

The code you’ve pasted doesn’t match the description you wrote of it,
unless I’m misunderstanding what you’re looking for.

If your column is called page_id rather than issue_id, you should put
the has_many line in the Page class, not the Issue class.

If only Issues should have many Articles, and not Pages, you can
either rename the column, or specify its name in the has_many call.

Wilson B. wrote:

On 5/10/06, Joe C. [email protected] wrote:
If only Issues should have many Articles, and not Pages, you can
either rename the column, or specify its name in the has_many call.

Exactly what I’m trying to do, thanks! How can I specify the name in
the has_many? I’m a little new to this rails thing…

On 5/10/06, Joe C. [email protected] wrote:

Wilson B. wrote:

On 5/10/06, Joe C. [email protected] wrote:
If only Issues should have many Articles, and not Pages, you can
either rename the column, or specify its name in the has_many call.

Exactly what I’m trying to do, thanks! How can I specify the name in
the has_many? I’m a little new to this rails thing…

Take a look at the :foreign_key option in the API docs:

Also, you may want to take a look at this, if you need something more
flexible down the road:
http://wiki.rubyonrails.org/rails/pages/UnderstandingPolymorphicAssociations