【问题标题】:Association between mongo and postgres modelmongo 和 postgres 模型之间的关联
【发布时间】:2018-09-20 20:02:06
【问题描述】:

我在一个应用中有两个数据库

  1. Postgres
  2. MongoDB

除了一个型号,所有型号都在Postgres 型号名称MessageMongoDB 中如下

  1. message.rb - MongoDB

    class Message
      include Mongoid::Document
    
      field :content,         type: String
      field :user_id,         type: Integer
    end
    
  2. user.rb - Postgres

    class User < ApplicationRecord
    end
    

现在我想将user 模型与message 模型相关联,以执行eagerloading。

如果我写belongs_to :user,然后执行Message.last.user,则会出现以下错误

NoMethodError (undefined method `_association' for []:Array)

有没有办法解决这个问题?

【问题讨论】:

    标签: ruby-on-rails mongodb postgresql ruby-on-rails-5.1


    【解决方案1】:

    您不能真正进行这样的跨数据库关联。但是,根据您需要多少关联,可能很容易伪造它:

    class Message
      include Mongoid::Document
    
      field :content,         type: String
      field :user_id,         type: Integer
    
      def user
        User.find(user_id)
      end
    end
    

    如果您不确定user_ids 的有效性,那么:

    def user
      User.find_by(id: user_id)
    end
    

    可能会更好,但您必须为nils 退出some_message.user 做好准备。您可能需要在 user_id 上添加一些验证,以确保它确实是 Userid

    当然,这种诡计不会帮助您将用户删除传播到 MongoDB 或在 User 中支持 has_many :messages。您也必须手动完成这些工作,但 after_destroy(或 around_destroy)钩子和几个简单的手写方法(和可靠的测试套件)可以填补这些空白。

    【讨论】:

    • 感谢您的回复,因为我已经这样做了,但这不是我的问题的答案,我想定义两个模型之间的关系。
    • 除非您手动完成,否则您无法建立跨数据库关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多