【问题标题】:Is there a method for polymorphic associate to non mongoid document?有没有一种方法可以将多态关联到非 mongoid 文档?
【发布时间】:2019-07-03 19:11:22
【问题描述】:

我有一个带有多态 orderalbe 字段的 Order 类。一些产品与 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?

【问题讨论】:

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


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多