0

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.

Nilloc
  • 845
  • 7
  • 20

1 Answers1

1

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
Padhu
  • 1,590
  • 12
  • 15
  • Thanks, I'm still getting the hang of Rails inheritance and I couldn't find the right set of keywords to answer. Where might I ask did you find the docs for this? – Nilloc Jan 08 '16 at 05:24
  • 1
    Hi, Rails official docs were really good http://guides.rubyonrails.org/association_basics.html and http://apidock.com/rails/ActiveRecord/Associations/AssociationCollection Recently I went through a ruby on rails course in coursera.org from John Hopkins University, It helped me a lot to understand various concepts better. Give it a go if you are free, by the way it is free. https://www.coursera.org/specializations/ruby-on-rails – Padhu Jan 08 '16 at 15:11