Raj*_*hra 6 ruby-on-rails associations data-synchronization
我将有两个Rails应用程序,一个是成熟的应用程序,另一个是简化的应用程序。这两个应用程序都有自己的数据库,它们将使用API相互通信。
我有两个这样的模型(在两个应用程序中):
class Scan < ApplicationRecord
has_many :background_processes, dependent: :destroy
end
class BackgroundProcess < ApplicationRecord
belongs_to :scan
end
Run Code Online (Sandbox Code Playgroud)
现在,当两个应用程序之间发生同步时,从属模型(在这种情况下background_processes)将具有不同的scan_id。
如果发生数据同步,我们应该如何处理关联?
小智 3
我建议在模型上使用另一个索引列scan,您可以在其中存储可用于查询扫描记录的另一个 id 或令牌。也许可以称之为sync_id什么的。
如果你采取这条路线,你就不必担心scan_id后台进程记录上的不同。请务必使用扫描的 JSON 正文发送后台进程记录。(假设您使用 JSON 作为 API 的格式。)
总体思路如下...您将确保您的发送 API 服务通过相关后台进程发送整个扫描记录。然后,接收 API 服务需要使用该扫描记录sync_id来查询现有扫描记录并更新它。您还需要在后台进程记录上使用某种唯一标识符,以确保不会创建重复项。如果需要,sync_id还可以在后台创建一个进程。如果具有该 id 的扫描记录不存在,则创建它以及依赖的后台进程。
本质上,发送服务的 API POST 请求可能如下所示:
{
id: 1,
sync_id: "sometoken"
... # other record columns
background_process: [
{
id: 123,
... # other record columns
}
]
}
Run Code Online (Sandbox Code Playgroud)
确保sync_id您使用的是唯一的。在扫描模型中使用类似的东西在 before_create 挂钩上生成它:
def set_sync_id
random_token = SecureRandom.urlsafe_base64
while Scan.where(sync_id: random_token).present? do
random_token = SecureRandom.urlsafe_base64
end
self.sync_id = random_token
end
Run Code Online (Sandbox Code Playgroud)