是否有一种方法可以将非多态文档与多态关联?

时间:2019-07-03 19:11:22

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

我有一个Order类,其中orderalbe字段是多态的。一些产品与Order相关联,例如Book。

如果Book是Mongoid :: Document,效果很好,但是某些产品不存储在本地数据库中,而不是通过API获取。

是否有处理此案的好方法?我应该实现一些与本地商店相同的方法吗?

  class Order
    include Mongoid::Document
    belongs_to :orderable, polymorphic: true
  end

  class Book
    include Mongoid::Document
  end

  class Car
    def self.find(id)
      # Fetch from API
      new Car()
    end
  end
o = Order.create(orderable_id: 1, orderable_type: 'Car')
o.orderable
=> nil  # why is nil? Not use self.find() method?

1 个答案:

答案 0 :(得分:1)

我通过查看mongoid的源代码找到了答案。如果其他人有类似的需求,希望能有所帮助。请让我知道是否有更好的解决方案。

我查看了mongoid的源代码,发现它实际上是由where语句(不是find方法)查询的。

class Car
  def self.where(*args)
    # Fetch from API
    [new(fetched_attributes_by_api)]
  end
end

o = Order.first
o.orderable
=> #<Car _id: 1>