首页 > 解决方案 > Rails 5 中的自引用关联

问题描述

我正在尝试在 Rails 5 中设置自引用关联。我有一个视频模型。一个视频可能有一个以前的视频(如电视连续剧)。理想情况下,它会像这样运行;

irb(main):001:0> first_video  = Video.create(url: 'https://youtu.be/W0lhlPdo0mw')
irb(main):002:0> second_video = Video.create(url: 'https://youtu.be/gQhlw6F603o', previous_video: first_video)
irb(main):003:0> second_video.previous_video
=> #<Video id: 1, url: "https://youtu.be/W0lhlPdo0mw">

这是我目前的方法,但它失败了,(PG::UndefinedColumn: ERROR: column videos.video_id does not exist)所以我不得不传递 id。

模型

class Video < ApplicationRecord
  has_one :previous_video, class_name: 'Video'
end

移民

class CreateVideo < ActiveRecord::Migration[5.2]
  def change
    create_table :videos do |t|
      t.string :url, null: false
      t.references :previous_video, class: 'Video'

      t.timestamps
    end
  end
end

在 Rails 5 中实现这一目标的最佳实践是什么?为什么上述工作没有按预期工作?干杯团队!

标签: ruby-on-railsactiverecordruby-on-rails-5

解决方案


您需要像这样设置关联:

has_one :prev_video, :class_name => 'Video', :foreign_key => 'previous_video'

设置好你可以调用

@video.prev_video

外键是数据库列,我称为 prev_video 的列可以随意命名,只要您不使用与 db 列相同的名称(previous_video)。


推荐阅读