Search code examples
ruby-on-railsruby-on-rails-3has-manysingle-table-inheritance

Using has_many with Multple Model Types via STI


How do I save and view a has_many relationship with 2 different models that are inheriting though STI?

I've got a base Model for Projects as follows:

class Project < ActiveRecord::Base
  attr_accessible :slug, 
                  :category_id, 
                  :description, 
                  :name, 
                  :visible, 
                  :note,
                  :contractor, :contractor_url, 
                  :date_complete, :architect, :architect_url, 
                  :building_year, 
                  :project_type, 
                  :address, :city, :state, :country,  
                  :pictures,
                  :photo_credit

  has_many :pictures, :order=>:id, :dependent => :destroy

Picture.rb:

class Picture < ActiveRecord::Base
  attr_accessible :project_id, :image, :caption, :cover, :dimensions

  belongs_to :project

And using STI I have Homepage Items which display a subset of Projects and are specific to the homepage:

class HomepageItem < Project
  attr_accessible :slug, 
                  :name, 
                  :visible, 
                  :note,
                  :pictures,
                  :photo_credit

  has_many :pictures, :order=>:id, :dependent => :destroy

This results in an error expecting a new column on pictures homepage_item_id instead of project_id

PG::UndefinedColumn: ERROR: column pictures.homepage_item_id does not exist
I believe this should be looking on the pictures.project_id column.

Note: Without the has_many defined in HomepageItem, the items are saved, but no Pictures are created. Also this is a Rails 3.2.22 project.


Solution

  • as you see it looking for foreign key, so include foreign key in the association like below,

    class HomepageItem < Project
      attr_accessible :slug, 
                      :name, 
                      :visible, 
                      :note,
                      :pictures,
                      :photo_credit
    
      has_many :pictures, :foreign_key =>:project_id, :order=>:id, :dependent => :destroy