ruby-on-rails - 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 中实现这一目标的最佳实践是什么?为什么上述工作没有按预期工作?干杯团队!
解决方案
您需要像这样设置关联:
has_one :prev_video, :class_name => 'Video', :foreign_key => 'previous_video'
设置好你可以调用
@video.prev_video
外键是数据库列,我称为 prev_video 的列可以随意命名,只要您不使用与 db 列相同的名称(previous_video)。
推荐阅读
- sql - C++/CLI SQL 使用 ConnectionString 和参数作为字符串
- node.js - 有没有办法限制收到的请求以模拟服务器超时?
- r - 来自多个列的平均值(错误消息)
- angular - 使用角度材料中的项目索引
- javascript - JS 总是加载默认视图
- multithreading - Julia 1.5.2 并行禁止 Gurobi 学术许可
- bash - 在 bash 脚本中更改文件的最佳方法
- c - C - 如何将用户字符输入转换为 ASCII
- android - 使用协程在 android 上解析改造响应的最佳实践是什么
- flowtype - Flow 是否适用于任何 JavaScript 框架?