【问题标题】:Multiple one-to-many associations in one model一个模型中的多个一对多关联
【发布时间】:2009-08-31 09:28:00
【问题描述】:

给定两个模型类,FooBar,我希望 Foo 使用 3 个不同的属性名称对 Bar 的单独实例进行 3 个引用,外键位于 Foo 表中。 Bar 将单独管理,可以属于 Foo 的多个实例。这在某种程度上解释了它,显然 has_one 是使用错误的关联(我认为?):

Foo
   has_one :prop_a, :class_name => "Bar"
   has_one :prop_b, :class_name => "Bar"
   has_one :prop_c, :class_name => "Bar"

Bar

有 3 种可能的 Bar 类型,由 bar_type 字符串字段表示,对 Foo 的每个引用对应于其中之一。例如Foo.prop_a 引用了一个带有 bar_type = 'type_a' 的 Bar 实例。如何在 Rails 中创建这种类型的关联?

【问题讨论】:

    标签: ruby-on-rails activerecord model


    【解决方案1】:

    你是对的,这里使用了错误的关联。

    在 ActiveRecord 中,他们为 具有外键的模型总是 belongs_to 另一个模型。

    在这个场景中,Foo 类实际上是 belongs_to 那些道具

    一种指定方式是:

    class Foo < ActiveRecord::Base
     belongs_to :prop_a, :class_name => "Bar", :foreign_key => "prop_a_id"
     belongs_to :prop_b, :class_name => "Bar", :foreign_key => "prob_b_id"
     belongs_to :prop_c, :class_name => "Bar", :foreign_key => "prob_c_id"
    end
    

    这意味着,您必须在 Foo 上有一个标题为“prop_a_id, prop_b_id, and prop_c_id”的列,它可以存储作为 Bar 表的主键的整数。

    但是,此解决方案无法解决 ActiveRecord 关联下方列出的问题。对于上面提出的解决方案,您需要查看 Rails 和 Single Table Inheritance。如果你用谷歌搜索,你可以在上面找到很多资源。就个人而言,我推荐使用 Rails 进行敏捷 Web 开发。在第 3 版中,您可以在第 377 页找到它。还有一篇关于 STI 的不错的初学者文章here

    祝你好运!

    【讨论】:

      【解决方案2】:

      为什么不使用继承。您可以创建 3 个继承自 Bar 的类。您需要做的就是在数据库中有一个类型列。

      class Foo
        has_one :bara
        has_one :barb
        has_one :barc
      end
      
      class BarA < Foo
        belongs_to :foo
      end
      
      class BarB < Foo
        belongs_to :foo
      end
      
      class BarC < Foo
        belongs_to :foo
      end
      

      那么您的迁移需要有 bara_id、barb_id 和 barc_id 列。

      我没有尝试过,但它应该可以工作。

      one = Foo.new
      two = BarA.new
      three = BarB.new
      four = BarC.new
      one.bara = two
      one.barb = three
      one.barc = four
      one.save
      
      one.bara.foo #=> one
      one.bara.bara = BarA.new
      one.bara.bara.foo #=> two
      

      【讨论】:

        【解决方案3】:

        【讨论】:

          猜你喜欢
          • 2012-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多