【问题标题】:Custom foreign_key in model gives PG::Error column does not exist - Rails模型中的自定义 foreign_key 给出 PG::Error 列不存在 - Rails
【发布时间】: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


【解决方案1】:

我并没有真正使用具有与标准不同的外键的 has_many 和 belongs_to,但根据文档我会这样做:

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

您的 Pg 错误表明关联正在寻找“video_collection_id”而不是“folder_id”

Guides(第 4.3.2.5 章)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2017-04-29
    • 2011-09-13
    • 2015-05-11
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多