【问题标题】:Rails inverse polymorphic associationRails 逆多态关联
【发布时间】:2013-09-10 19:04:39
【问题描述】:

我熟悉使用 Rails 的多态关联,其中可以将模型声明为多态以获得属于多个其他模型的能力,例如:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

class Article < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Photo < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Event < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

是否有一种常见的模式来处理相反的情况,其中一个模型可以有许多其他模型可以通过相同的接口访问(例如,一个人有很多宠物,其中宠物可以是狗、猫、 ETC。)?我应该只创建一个虚拟属性吗?

【问题讨论】:

  • 您找到解决方案了吗?我正在寻找类似的东西。虽然,STI 可能适用于您的宠物示例。

标签: ruby-on-rails polymorphism polymorphic-associations


【解决方案1】:

以您的宠物为例,STI 可能是一个解决方案:

class Person < ActiveRecord::Base
  has_many :pets
end

class Pet < ActiveRecord::Base
  belongs_to :owner, class_name: "Person", foreign_key: "person_id"
  # Be sure to include a :type attribute for STI to work
end

class Dog < Pet
end

class Cat < Pet
end

这仍然可以让您访问@person.pets 和@dog.owner、@pet.owner 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2019-03-14
    • 2016-04-05
    • 1970-01-01
    相关资源
    最近更新 更多