【发布时间】:2019-01-11 23:22:37
【问题描述】:
我正在尝试在 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 中实现这一目标的最佳实践是什么?为什么上述工作没有按预期工作? 干杯!
【问题讨论】:
-
错误原因是因为t.references会在db中创建
previous_video_id,而不是video_id。如果您查看您的架构文件,您应该能够看到这一点。
标签: ruby-on-rails activerecord ruby-on-rails-5