【发布时间】:2014-05-06 10:11:32
【问题描述】:
我有一个VideoCollection 模型,它将包含来自另一个模型(称为VideoWork)的许多记录,使用has_many 关系。 VideoCollection 模型使用单表继承从Collection 模型继承,而VideoWork 模型从Work 模型继承。
我在尝试调用属于 video_collection 的 video_works 时遇到问题。
在我的video_collection#show 操作中,我使用以下内容来尝试显示收藏的作品:
def show
@video_collection = VideoCollection.find(params[:id])
@collections = @video_collection.children
@works = @video_collection.video_works
end
但是当我尝试在 show 视图中使用 @works 时,我得到以下信息:
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| %>)
我的模型文件:
#----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
“父”模型:
#----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
架构文件:
#----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
我的问题
我假设因为我在works 表中有一个folder_id 列,我应该能够正确设置belongs_to 关系,但似乎Rails 仍然希望我有一个video_collection_id 列反而。我不希望在works 表中使用像video_collection_id 这样的特定内容作为外键,因为我需要设置其他关系(例如:photo_collection has_many photo_works 等)。
我在这里做错了什么?
【问题讨论】:
-
尝试将
belongs_to association放入Work模型本身。 -
@Pavan - 我将整行
belongs_to :folder, class_name: "VideoCollection", foreign_key: "folder_id"从VideoWork模型文件中移到Work文件中,但不幸的是,我仍然遇到同样的错误。
标签: ruby-on-rails postgresql foreign-keys belongs-to