【问题标题】:Is it ok to make http calls from a Rails Model?可以从 Rails 模型进行 http 调用吗?
【发布时间】:2017-10-11 19:19:50
【问题描述】:

我正在集成我的系统和外部网络服务。在我的系统中,我有一个 Customer 模型。客户可以借记,但我的数据库中没有此信息(客户的财务状况)。它在我正在与之集成的网络服务中。

我在这个模型中创建了一个方法并将其命名为is_in_debit?。在方法实现中,我正在对 Web 服务进行 HTTP 调用。

class Customer < ActiveRecord::Base
  ...

  def is_in_debit?
    response = HTTP.get_response('https://...').body
    response = JSON.parse(response)

    response['status'] == 'active' ? false : true
  end
end

但我怀疑该模型是否是进行 HTTP 调用的正确位置。从建筑的角度来看,对吗?还是我应该改变我的方法?

【问题讨论】:

  • 没问题 - 是的,不,取决于。创建服务对象或某种客户端通常是一个更好的主意,因为 Rails 中的模型已经塞满了很多责任。

标签: ruby-on-rails web-services activerecord model-view-controller architecture


【解决方案1】:

不,您违反了SRP principle,在活动记录模型中,您应该只添加访问模型数据的方法。 我建议创建一个新对象:

class CustomerService
  def is_in_debit?(user)
     // your http request here
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多