【问题标题】:Is it possible to have a dynamic id column in Rails 3 when using single table inheritance使用单表继承时是否可以在 Rails 3 中有动态 id 列
【发布时间】:2013-01-01 18:18:13
【问题描述】:

我有一个 Change 模型,它利用具有以下属性的单表继承:

id
type    #this is a single table inheritance type field.
description
dynamic_id

我还有两个子类,Race 是 Change 的子类,Workout 是 Race 的子类。

class Race < Change

end

class Workout < Race

end

我有第四个名为 Track 的类,我想通过使用 Change 对象中的 dynamic_id 字段来创建以下四个关联。 (即,我没有明确地将race_id 和锻炼ID 添加到更改表中。相反,我想使用dynamic_id 作为Race 类的race_id,使用dynamic_id 作为Workout 类的锻炼ID)通过这样做,我将避免很多我的数据库中的 nil 字段。)

这是我正在尝试创建的四个关联。

  1. 种族模型 - belongs_to :track
  2. 锻炼模型 - belongs_to :track
  3. 赛道模型 - has_many :races
  4. 跟踪模型 - has_many :workouts

我一直在尝试通过使用 :class_name 和 :foreign_key 的关联来完成此操作,但我似乎无法使其正常工作。这真的可能吗。我意识到这可能不是最佳实践,但我仍然想看看它是否可行。感谢您的意见。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 single-table-inheritance


    【解决方案1】:

    您正在寻找的是“多态关联”。您可以在 Rails 指南中找到更多信息:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

    您的情况有点特殊,因为您想对 STI 使用多态关联。我记得这个组合有一个错误,但现在可以修复了。

    我没有完整阅读,但这篇博文似乎描述了这种情况:http://www.archonsystems.com/devblog/2011/12/20/rails-single-table-inheritance-with-polymorphic-association/

    我遇到的多态关联和 STI 问题描述如下:Why polymorphic association doesn't work for STI if type column of the polymorphic association doesn't point to the base model of STI?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 2012-01-20
      • 1970-01-01
      • 2010-10-08
      相关资源
      最近更新 更多