【问题标题】:Rails: one of many parentsRails:众多父母之一
【发布时间】:2014-10-21 18:08:19
【问题描述】:

如果我有一个模型可以属于其他十个模型之一,我是否需要模型中的十个不同的_id 属性,每条记录留九个空白?或者有没有更好的安排方式?

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 has-many-through has-many


    【解决方案1】:

    正如 Jakub 建议的那样,您可以使用 polymorphism,如下所示:

    class Bar < ActiveRecord::Base
      belongs_to :foo, polymorphic: true
      ...
    end
    
    class Foo1 < ActiveRecord::Base
      has_many :bars, as: :foo
      ...
    end
    
    class Foo2 < ActiveRecord::Base
      has_many :bars, as: :foo
      ...
    end
    
    ...
    
    class Foo9 < ActiveRecord::Base
      has_many :bars, as: :foo
    end
    

    这将使用bars 表中的单个id 属性,但包含一个额外的类型字段来指定它所指的foo 类型。

    【讨论】:

    • 感谢您提供详细信息!
    【解决方案2】:

    多态关联呢?如果你需要一个模型属于许多其他模型。那么你只需要_id和_type,它们不会为空。http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

    我需要模型中有十个不同的 _id 属性,每条记录留九个空白? - 没有

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多