简体   繁体   English

RoR:同一模型中的has_one和has_many引用?

[英]RoR: a has_one and has_many reference in same model?

Say I have a model called Device, and another model called Firmware (which contains a firmware version number and other info). 假设我有一个名为Device的模型,另一个名为Firmware的模型(包含固件版本号和其他信息)。 I would like to keep track of the history of firmware versions installed on the device, but also a reference to the current version (which may or may not be the most recent date-wise). 我想跟踪设备上安装的固件版本的历史记录,还要参考当前版本(可能是也可能不是最新的日期版本)。

How do I set up my associations so that I can point to one specific firmware configuration (the current one) and also several different firmware configurations (the history)? 如何设置关联以便指向一个特定的固件配置(当前固件配置)以及几个不同的固件配置(历史记录)?

Add device_current_id integer column to the firmwares table and then: device_current_id整数列添加到固件表,然后:

class Device < ActiveRecord::Base
  ...
  has_one :current_firmware, class_name: "Firmware", foreign_key: "device_current_id"
  has_many :firmwares
end

Use :class_name in you associations like... 在你的关联中使用:class_name ...

Device Model 设备模型

has_one :current_firmware, class_name :firmware
has_many :old_firmwares, class_name :firmware

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM