Question

I have a VideoCollection model that will contain many records from another model (called VideoWork), using the has_many relationship. The VideoCollection model inherits from the Collection model using single table inheritance, while the VideoWork model inherits from the Work model.

I'm having a problem when I try to call up the video_works that belong to a video_collection. In my video_collection#show action, I use the following to try to display a collection's works:

def show
  @video_collection = VideoCollection.find(params[:id])
  @collections = @video_collection.children
  @works = @video_collection.video_works
end

But when I try to use @works in the show view, I get the following:

PG::Error: ERROR:  column works.video_collection_id does not exist
SELECT "works".* FROM "works"  WHERE "works"."type" IN ('VideoWork') AND "works"."video_collection_id" = $1

##(Error occurs in the line that contains <% @works.each do |work| %>)


My model files:

#----app/models/video_collection.rb----
    class VideoCollection < Collection
      has_many :video_works
    end

#----app/models/video_work.rb----
    class VideoWork < Work
      belongs_to :folder, class_name: "VideoCollection", foreign_key: "folder_id"
    end

The "parent" models:

#----app/models/collection.rb - (VideoCollection inherits from this)
    class Collection < ActiveRecord::Base
    end    

#----app/models/work.rb - (VideoWork inherits from this)
    class Work < ActiveRecord::Base
    end

The Schema file:

#----db/schema.rb----
    create_table "works", force: true do |t|
      t.string "header"
      t.string "description"
      t.string "type"
      t.string "folder_id"
    end

  create_table "collections", force: true do |t|
    t.string   "type"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.text     "ancestry"
    t.string   "name"
    t.string   "tile_image_link"
end


My Question

I assume that since I have a folder_id column in the works table that I should be able to set up the belongs_to relationship properly, but it seems that Rails still wants me to have a video_collection_id column instead. I would prefer not use something specific like video_collection_id as a foreign key in the works table since I need to set up other relationships (e.g.: photo_collection has_many photo_works, etc).

What am I doing wrong here?

Was it helpful?

Solution

I don't really use has_many and belongs_to with different foreign keys than the standard, but according to the docs I would do this:

class VideoCollection < Collection
  has_many :video_works, foreign_key: "folder_id"
end

class VideoWork < Work
  belongs_to :folder, class_name: "VideoCollection", foreign_key: "folder_id"
end

Your Pg error says that the association is looking for 'video_collection_id' instead of 'folder_id'

Guides (chapter 4.3.2.5)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top